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
| struct Fenwick { int tr[N]; void add(int x, int c) { if (!x) return puts("Failed"), void(); for (; x < N; x += (x & -x)) tr[x] += c; } int ask(int x) { int res = 0; for (; x; x ^= (x & -x)) res += tr[x]; return res; } } T1, T2;
inline int find(int x) { return x == f[x] ? x : f[x] = find(f[x]); }
void dfs(int x, int fa = 0) { nw[dfn[x] = ++ *dfn] = x, ::fa[x] = fa, sz[x] = 1; for (int v : g[x]) if (v ^ fa) dfs(v, x), sz[x] += sz[v]; }
int ask(Fenwick &T, int x) { return T.ask(dfn[x] + sz[x] - 1) - T.ask(dfn[x] - 1); }
void update(int x) { if (vis[x] || x == 1) return; vis[x] = true; assert(f[x] == x); int sz = ask(T1, x), sum = ask(T2, x), anc; f[x] = find(fa[x]), anc = find(x); T2.add(dfn[fa[x]], sum), T1.add(dfn[fa[x]], sz); if (fa[anc]) T1.add(dfn[fa[anc]], -sz), T2.add(dfn[fa[anc]], -sum); assert(ask(T1, anc) >= 0 && ask(T2, anc) >= 0); pq.push({ask(T2, anc) / ask(T1, anc) - 1, anc}); }
signed main() { std::cin >> n; for (int i = 1; i <= n; ++ i) f[i] = i; for (int i = 1, u, v; i < n; ++ i) { scanf("%lld %lld", &u, &v); g[u].push_back(v), g[v].push_back(u); } std::cin >> Q; for (int i = 1; i <= Q; ++ i) scanf("%lld %lld", &q[i].u, &q[i].k), q[i].id = i; std::sort(q + 1, q + Q + 1, [&](Query &q1, Query &q2) { return q1.k > q2.k; }); dfs(1); for (int i = 1; i <= n; ++ i) { T1.add(dfn[i], 1), son[i] = g[i].size() - (i > 1); T2.add(dfn[i], son[i]); if (i ^ 1) T1.add(dfn[fa[i]], -1), T2.add(dfn[fa[i]], -son[i]), pq.push({son[i] - 1, i}); } for (int i = 1, x; i <= Q; ++ i) { while (!pq.empty() && pq.top().first >= q[i].k) x = pq.top().second, pq.pop(), update(x); res[q[i].id] = ask(T2, q[i].u) - (q[i].k + 1) * ask(T1, q[i].u) + 1 + q[i].k; } for (int i = 1; i <= Q; ++ i) printf("%lld\n", res[i]); return 0; }
|