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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| #include<bits/stdc++.h> using namespace std; using LL = long long; const int N = 3e5 + 5, MOD = 998244353, INF = 0x3f3f3f3f;
int n, m, w[N]; vector< int > adj[N]; int dep[N], top[N], son[N], siz[N], f[N]; void dfs1(int x, int p) { dep[x] = dep[p] + 1; siz[x] = 1; f[x] = p; for (const auto &y : adj[x]) { if (y ^ p) { dfs1(y, x); siz[x] += siz[y]; if (siz[y] > siz[son[x]]) { son[x] = y; } } } } void dfs2(int x, int tp) { top[x] = tp; if (!son[x]) { return; } dfs2(son[x], tp); for (const auto &y : adj[x]) { if (y != son[x] && y != f[x]) { dfs2(y, y); } } } int lca(int x, int y) { while (top[x] != top[y]) { if (dep[top[x]] < dep[top[y]]) { swap(x, y); } x = f[top[x]]; } return dep[x] > dep[y] ? y : x; } int rt[N], ls[N << 6], rs[N << 6], cnt[N << 6], tot; void Modify(int &x, int l, int r, int p, int k) { if (!x) { x = ++ tot; } if (l == r) { cnt[x] += k; return; } int mid = (l + r) >> 1; if (p <= mid) { Modify(ls[x], l, mid, p, k); } else { Modify(rs[x], mid + 1, r, p, k); } } int Merge(int x, int y, int l, int r) { if (!x || !y) { return x | y; } int z = ++ tot; if (l == r) { cnt[z] = cnt[x] + cnt[y]; } else { int mid = (l + r) >> 1; ls[z] = Merge(ls[x], ls[y], l, mid); rs[z] = Merge(rs[x], rs[y], mid + 1, r); } return z; } int Query(int x, int l, int r, int p) { if (!x) { return 0; } if (l == r) { return cnt[x]; } int mid = (l + r) >> 1; if (p <= mid) { return Query(ls[x], l, mid, p); } return Query(rs[x], mid + 1, r, p); } int ans[N]; void dfs(int x, int p) { for (const auto &y : adj[x]) { if (y ^ p) { dfs(y, x); rt[x] = Merge(rt[x], rt[y], -n, n); } } if (dep[x] + w[x] <= n) { ans[x] += Query(rt[x], -n, n, dep[x] + w[x]); } if (dep[x] - w[x] >= -n) { ans[x] += Query(rt[x], -n, n, dep[x] - w[x]); } if (!w[x]) { ans[x] >>= 1; } } signed main() { cin.tie(nullptr)->sync_with_stdio(false);
cin >> n >> m; for (int i = 1; i < n; ++ i) { int u, v; cin >> u >> v; adj[u].push_back(v); adj[v].push_back(u); } dfs1(1, 0); dfs2(1, 1); for (int i = 1; i <= n; ++ i) { cin >> w[i]; } while (m -- ) { int s, t; cin >> s >> t; int kk = lca(s, t); Modify(rt[s], -n, n, dep[s], 1); Modify(rt[f[kk]], -n, n, dep[s], -1); Modify(rt[t], -n, n, 2 * dep[kk] - dep[s], 1); Modify(rt[kk], -n, n, 2 * dep[kk] - dep[s], -1); } dfs(1, 0); for (int i = 1; i <= n; ++ i) { cout << ans[i] << " \n"[i == n]; } return 0; }
|