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
| #include <bits/stdc++.h> using namespace std; const int N = 1e5 + 1, M = 2 * N, K = 21; int n, k, u, v; int c[N], h[N], e[M], ne[M], idx; int dp[N][K]; void add(int u, int v) { e[++idx] = v, ne[idx] = h[u], h[u] = idx; } int main() { scanf("%d%d", &n, &k); for (int i = 1; i < n; ++i) { scanf("%d%d", &u, &v); add(u, v), add(v, u); } for (int i = 1; i <= n; ++i) scanf("%d", &c[i]); function<void(int, int)> dfs = [&](int u, int f) { dp[u][0] = c[u]; for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { dfs(v, u); for (int j = 1; j <= k; ++j) dp[u][j] += dp[v][j - 1]; } } }; dfs(1, 0); function<void(int, int)> reroot = [&](int u, int f) { for (int i = h[u]; i; i = ne[i]) { int v = e[i]; if (v != f) { for (int j = k; j >= 2; --j) dp[v][j] -= dp[v][j - 2]; for (int j = 1; j <= k; ++j) dp[v][j] += dp[u][j - 1]; reroot(v, u); } } }; reroot(1, 0); for (int i = 1; i <= n; ++i) printf("%d\n", accumulate(dp[i], dp[i] + k + 1, 0)); return 0; }
|