AcWing 1153. 括号树
原题链接
中等
作者:
霁
,
2019-12-14 10:08:03
,
所有人可见
,
阅读 800
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 5e5 + 10;
int f[N];
char ch[N];
int s[N];
int n;
int head[N];
int top = 0, tot = 0;
long long ans, sum[N], d[N];
struct Edge
{
int ver;
int next;
} a[N];
inline void add(int x, int y)
{
a[++tot].ver = y;
a[tot].next = head[x];
head[x] = tot;
}
void dfs(int x)
{
int t = 0;
if(ch[x] == '(')
s[++top] = x;
else if(ch[x] == ')')
if(top != 0)
{
t = s[top];
d[x] = d[f[s[top--]]] + 1;
}
sum[x] = sum[f[x]] + d[x];
for(int i = head[x]; i; i = a[i].next)
dfs(a[i].ver);
if(t != 0)
s[++top] = t;
else if(top != 0)
--top;
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
memset(head, 0, sizeof(head));
memset(d, 0, sizeof(d));
for(int i = 1; i <= n; i++)
cin >> ch[i];
for(int i = 2; i <= n; i++)
{
cin >> f[i];
add(f[i], i);
}
f[1] = 1;
dfs(1);
for(register long long i = 1; i <= n; i++)
ans ^= i * sum[i];
cout << ans;
return 0;
}