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
| #include<bits/stdc++.h> #define MAXN 100005 using namespace std; int n, m, c[MAXN]; int siz[MAXN], son[MAXN]; int cnt[MAXN], cntt[MAXN]; int ans[MAXN], Ans; namespace F_star { int cnte = 0, head[MAXN]; struct edge { int to, nxt; }e[MAXN << 1]; void adde(int u, int v) { e[++cnte].to = v; e[cnte].nxt = head[u]; head[u] = cnte; } }using namespace F_star; struct query { int id, val; }; vector <query> v[MAXN];
void dfs(int u, int fa) { siz[u] = 1; for(int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa) continue; dfs(v, u); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } }
void add(int u) { cnt[c[u]]++; cntt[cnt[c[u]]]++; } void del(int u) { cntt[cnt[c[u]]]--; cnt[c[u]]--; }
void adds(int u, int fa) { add(u); for(int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa) continue; adds(v, u); } } void clannad(int u, int fa) { del(u); for(int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa) continue; clannad(v, u); } }
void dsu(int u, int fa) { for(int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa || v == son[u]) continue; dsu(v, u); clannad(v, u); } if(son[u]) dsu(son[u], u); for(int i = head[u]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa || v == son[u]) continue; adds(v, u); } add(u); for(int i = 0; i < v[u].size(); i++) ans[v[u][i].id] = cntt[v[u][i].val]; }
int main() { scanf("%d%d",&n, &m); for(int i = 1; i <= n; i++) scanf("%d",&c[i]); for(int i = 1; i < n; i++) { int u, v; scanf("%d%d", &u, &v); adde(u, v); adde(v, u); }
for(int i = 1; i <= m; i++) { int u, k; scanf("%d%d",&u,&k); v[u].push_back(query{i, k}); } dfs(1, 0); dsu(1, 0); for(int i = 1; i <= m; i++) printf("%d\n", ans[i]); return 0; }
|