\(50pts\)
#include
#include
#include
#include
using namespace std;
const int A = 5e5 + 11;
const int B = 1e6 + 11;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
inline int read() {
char c = getchar(); int x = 0, f = 1;
for( ; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
return x * f;
}
struct node {
int nxt, to;
} e[A << 1];
int n, cnt, head[A], f[A], ans[A], top = 0;
char sta[A], ss[A], a[A];
inline void add(int from, int to) {
e[++cnt].to = to;
e[cnt].nxt = head[from];
head[from] = cnt;
}
int jisuan() {
int tp = 0, res = 0;
for(int i = top; i >= 1; i--) {
if(sta[i] == ')') ++tp;
else {
if(tp > 0) tp--;
else break;
}
if(tp == 0) res++;
}
return res;
}
void dfs(int now, int fa) {
for(int i = head[now]; i; i = e[i].nxt) {
int to = e[i].to;
sta[++top] = a[to];
if(a[to] == '(') ans[to] = ans[now];
else ans[to] = ans[now] + jisuan();
dfs(to, now);
top--;
}
}
int main() {
n = read(); scanf("%s", a + 1);
for(int i = 2, x; i <= n; i++) {
x = read();
f[i] = x;
add(x, i);
}
sta[++top] = a[1];
dfs(1, 0);
int sum = 0;
for(int i = 1; i <= n; i++) {
sum ^= (i * ans[i]);
}
cout << sum << '\n';
return 0;
}
\(100pts\):
#include
#include
#include
#include
#define int long long
using namespace std;
const int A = 5e5 + 11;
const int B = 1e6 + 11;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
inline int read() {
char c = getchar(); int x = 0, f = 1;
for( ; !isdigit(c); c = getchar()) if(c == '-') f = -1;
for( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
return x * f;
}
struct node { int nxt, to; } e[A << 1];
int n, cnt, head[A], f[A], ans[A], top = 0, sum, sta[A];
char ss[A], a[A];
inline void add(int from, int to) {
e[++cnt].to = to;
e[cnt].nxt = head[from];
head[from] = cnt;
}
void dfs(int now, int faans, int top) {
int tp = 0;
if(a[now] == '(') sta[++top] = now;
else if(a[now] == ')') {
if(top == 0) ans[now] = 0;
else ans[now] = ans[f[sta[top]]] + 1, tp = sta[top], faans += ans[now], top--;
}
sum = sum ^ (faans * now);
for(int i = head[now]; i; i = e[i].nxt) {
int to = e[i].to;
dfs(to, faans, top);
}
if(tp) sta[++top] = tp;
}
signed main() {
n = read(); scanf("%s", a + 1);
for(int i = 2, x; i <= n; i++) {
x = read();
f[i] = x;
add(x, i);
}
dfs(1, 0, 0);
cout << sum << '\n';
return 0;
}