10pts
https://www.luogu.com.cn/record/30924231
不是妹子,刚学OI
#include<bits/stdc++.h>
using namespace std;
struct Node {
char ch;
int parent;
vector<int> sub;
};
Node tree[500010];
long long dp[500010];
stack<int> last;
long long ans;
void dfs(int node);
int main(void) {
int n;
scanf("%d", &n);
string s;
cin >> s;
for (register int i = 1; i <= n; ++i) {
tree[i].ch = s[i - 1];
tree[i].parent = 0;
tree[i].sub.clear();
}
for (register int i = 2; i <= n; ++i) {
scanf("%d", &(tree[i].parent));
tree[tree[i].parent].sub.push_back(i);
}
dfs(1);
for (register int i = 1; i <= n; ++i) {
ans ^= (long long)(i) * dp[i];
}
printf("%lld\n", ans);
return 0;
}
void dfs(int node) {
if (tree[node].ch == '(') {
dp[node] = dp[tree[node].parent];
last.push(node);
for (register int i = 0; i < tree[node].sub.size(); ++i) {
dfs(tree[node].sub[i]);
}
last.pop();
}
else {
if (last.empty()) {
dp[node] = dp[tree[node].parent];
for (register int i = 0; i < tree[node].sub.size(); ++i) {
dfs(tree[node].sub[i]);
}
}
else {
if (last.top() == 1 || tree[tree[last.top()].parent].ch == '(') {
dp[node] = dp[tree[node].parent] + 1;
int tmp = last.top();
last.pop();
for (register int i = 0; i < tree[node].sub.size(); ++i) {
dfs(tree[node].sub[i]);
}
last.push(tmp);
}
else {
dp[node] = dp[tree[node].parent] + dp[tree[last.top()].parent] + 1;
int tmp = last.top();
last.pop();
for (register int i = 0; i < tree[node].sub.size(); ++i) {
dfs(tree[node].sub[i]);
}
last.push(tmp);
}
}
}
return;
}