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
| #include <iostream> #include <cstdio> #include <vector>
using namespace std;
const int N = 1e5 + 5;
template <typename T> void read(T &x) { x = 0; char c = getchar(); while(!isdigit(c)) c = getchar(); while(isdigit(c)) x = x * 10 + c - '0', c = getchar(); return; }
template <typename T> void write(T x) { if(x > 9) write(x / 10); putchar(x % 10 + '0'); }
int n, m, col[N]; vector <int> g[N]; struct query { int k, id; }; vector <query> q[N]; int siz[N], son[N], f[N];
void dfs1(int u, int fa) { f[u] = fa; siz[u] = 1; for(int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if(v == fa) continue; dfs1(v, u); siz[u] += siz[v]; if(siz[v] > siz[son[u]]) son[u] = v; } }
int cnt[N], sum, ans[N], d[N];
void add(int u, int val, int Son) { cnt[col[u]] += val; if(val == 1) d[cnt[col[u]]]++; else d[cnt[col[u]] + 1]--; for(int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if(v == f[u] || v == Son) continue; add(v, val, Son); } }
void dfs2(int u, int op) { for(int i = 0; i < g[u].size(); i++) { int v = g[u][i]; if(v == f[u] || v == son[u]) continue; dfs2(v, 0); } if(son[u]) dfs2(son[u], 1); add(u, 1, son[u]); for(int i = 0; i < q[u].size(); i++) ans[q[u][i].id] = d[q[u][i].k]; if(!op) add(u, -1, 0), sum = 0; }
int main() { read(n), read(m); for(int i = 1; i <= n; i++) read(col[i]); for(int i = 1, u, v; i < n; i++) { read(u), read(v); g[u].push_back(v); g[v].push_back(u); } for(int i = 1, u; i <= m; i++) { query t; read(u), read(t.k); t.id = i; q[u].push_back(t); } dfs1(1, 0); dfs2(1, 0); for(int i = 1; i <= m; i++) write(ans[i]), puts(""); return 0; }
|