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
| #include <iostream> #include <cstdio>
const int z[2] = {-1, 1};
int n, m; int c[112345]; struct Edge { int from, to, next; } edge[212345]; int tot, head[112345]; int sz[112345], son[112345], cnt[112345]; int res, ans[112345];
void Addedge(int u, int v) { edge[++ tot] = (Edge){u, v, head[u]};
head[u] = tot; }
void Dfs1(int u, int fa) { sz[u] = 1;
for(int i = head[u]; i; i = edge[i].next) { int v = edge[i].to;
if(v == fa) continue;
Dfs1(v, u); sz[u] += sz[v];
if(sz[v] > sz[son[u]]) son[u] = v; } }
void Bf(int u, int fa, int x) { cnt[c[u]] += z[x]; if(cnt[c[u]] == x) res += z[x];
for(int i = head[u]; i; i = edge[i].next) { int v = edge[i].to;
if(v == fa) continue;
Bf(v, u, x); } }
void Dfs2(int u, int fa, bool dlt) { for(int i = head[u]; i; i = edge[i].next) { int v = edge[i].to;
if(v == fa || v == son[u]) continue;
Dfs2(v, u, true); } if(son[u]) Dfs2(son[u], u, false);
for(int i = head[u]; i; i = edge[i].next) { int v = edge[i].to;
if(v == fa || v == son[u]) continue;
Bf(v, u, 1); }
if(! cnt[c[u]]) res ++; cnt[c[u]] ++;
ans[u] = res;
if(dlt) Bf(u, fa, 0); }
int main() { scanf("%d", &n); for(int i = 1; i < n; i ++) { int u, v; scanf("%d%d", &u, &v);
Addedge(u, v); Addedge(v, u); } for(int i = 1; i <= n; i ++) scanf("%d", &c[i]);
Dfs1(1, 0); Dfs2(1, 0, true);
scanf("%d", &m); for(int i = 1; i <= m; i ++) { int x; scanf("%d", &x);
printf("%d\n", ans[x]); }
return 0; }
|