洛谷 P5658 括号树

\(50pts\)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
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;
}

猜你喜欢

转载自www.cnblogs.com/loceaner/p/12008301.html