1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| # include <bits/stdc++.h>
# define R register
const int MaxN = 1000010;
struct node//节点 { int val; int l, r; };
node a[MaxN]; int f[MaxN], val[MaxN], ind[MaxN];
inline void read(int &x) { x = 0; bool op = 1; char ch = getchar(); while(ch > '9' || ch < '0') { if(ch == '-') op = 0; ch = getchar(); } while(ch <= '9' && ch >= '0') x = (x << 1) + (x << 3) + (ch - '0'), ch = getchar(); if(!op) x = -x; }
void dfs(int root) { if(root == -1) return; if(a[root].l == -1 && a[root].r == -1) f[root] = 1, val[root] = a[root].val; else { dfs(a[root].l); dfs(a[root].r); f[root] = f[a[root].l] + f[a[root].r] + 1; val[root] = val[a[root].l] + val[a[root].r] + a[root].val; }
}
inline int check(int x) { std::queue<int> l, r; l.push(x), r.push(x); while(!l.empty() || !r.empty()) { if(l.empty() || r.empty()) return false; R int lx = l.front(), rx = r.front(); l.pop(), r.pop(); if(a[lx].val != a[rx].val) return false; R int lson[3], rson[3]; lson[1] = a[lx].l, lson[2] = a[lx].r; rson[1] = a[rx].l, rson[2] = a[rx].r; if((lson[1] == -1 && rson[2] != -1) || (lson[1] != -1 && rson[2] == -1)) return false; if((lson[2] == -1 && rson[1] != -1) || (lson[2] != -1 && rson[1] == -1)) return false; if(lson[1] != -1) l.push(lson[1]); if(lson[2] != -1) l.push(lson[2]); if(rson[2] != -1) r.push(rson[2]); if(rson[1] != -1) r.push(rson[1]); } return true; }
int main() {
R int n; scanf("%d", &n); for(R unsigned i = 1; i <= n; ++i) read(a[i].val); for(R unsigned i = 1; i <= n; ++i) read(a[i].l), read(a[i].r), ++ind[a[i].l], ++ind[a[i].r]; R unsigned root; for(R unsigned i = 1; i <= n; ++i) { if(!ind[i]) { root = i; break; } } dfs(root); int ans = 1; for(R unsigned i = 1; i <= n; ++i) { if(f[a[i].l] != f[a[i].r]) continue; if(val[a[i].l] != val[a[i].r]) continue; if(f[i] < ans || f[i] == 1) continue; if(check(i)) ans = f[i]; } printf("%d", ans); fclose(stdin); fclose(stdout); return 0; }
|