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
| #include <cstdio> using namespace std; const int N = 1e5 + 10, M = N << 1, K = 30; int n, k, c[N], f[N][K], s[N]; int idx, hd[N], nxt[M], edg[M]; void dfs1(int x, int fa) { f[x][0] = c[x]; for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != fa) { dfs1(edg[i], x); for (int j = 1; j <= k; j++) f[x][j] += f[edg[i]][j - 1]; } } void dfs2(int x, int fa) { for (int i = 0; i <= k; i++) s[x] += f[x][i]; for (int i = hd[x]; ~i; i = nxt[i]) if (edg[i] != fa) { for (int j = 1; j <= k; j++) f[x][j] -= f[edg[i]][j - 1]; for (int j = 1; j <= k; j++) f[edg[i]][j] += f[x][j - 1]; dfs2(edg[i], x); for (int j = 1; j <= k; j++) f[edg[i]][j] -= f[x][j - 1]; for (int j = 1; j <= k; j++) f[x][j] += f[edg[i]][j - 1]; } } void add(int a, int b) { nxt[++idx] = hd[a]; hd[a] = idx; edg[idx] = b; } int main() { scanf("%d%d", &n, &k); for (int i = 1; i <= n; i++) hd[i] = -1; for (int i = 1, u, v; 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]); dfs1(1, 0); dfs2(1, 0); for (int i = 1; i <= n; i++) printf("%d\n", s[i]); return 0; }
|