You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.7 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
2 years ago
#define int long long
#define endl "\n"
int n, q;
2 years ago
const int N = 200010, K = 21;
int head[N], dp[N][K];
2 years ago
struct ljj {
2 years ago
int to, stb;
2 years ago
} a[N];
int s;
void insert(int x, int y) {
2 years ago
s++;
a[s].stb = head[x];
a[s].to = y;
head[x] = s;
}
2 years ago
void dfs1(int x, int fa) {
2 years ago
for (int i = head[x]; i; i = a[i].stb) {
int xx = a[i].to;
2 years ago
if (xx == fa)
continue;
2 years ago
dfs1(xx, x);
2 years ago
for (int j = 1; j <= q; j++)
2 years ago
dp[x][j] += dp[xx][j - 1]; // 第一遍dp
}
}
2 years ago
void dfs2(int x, int fa) {
2 years ago
for (int i = head[x]; i; i = a[i].stb) {
int xx = a[i].to;
if (xx == fa) continue;
2 years ago
// 在第一次遍历时 dp[1][2] 包括了 dp[2][1] 2的子树权值
// 然鹅 ans在统计dp[2][3] 的时候也加上了 dp[2][1] 2的子树权值
// 第二次遍历 dp[2][3] 又加上了 dp[2][1];
// 所以需要简单容斥一下;
2 years ago
for (int j = q; j >= 2; j--)
2 years ago
dp[xx][j] -= dp[xx][j - 2]; // 简单容斥
2 years ago
for (int j = 1; j <= q; j++)
2 years ago
dp[xx][j] += dp[x][j - 1]; // 第二遍dp
2 years ago
dfs2(xx, x);
2 years ago
}
}
2 years ago
signed main() {
cin >> n >> q;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
2 years ago
insert(x, y);
insert(y, x);
}
2 years ago
for (int i = 1; i <= n; i++) cin >> dp[i][0]; // 每个节点往外0距离就是它本身的权值
2 years ago
dfs1(1, 0);
2 years ago
dfs2(1, 0);
2 years ago
for (int i = 1; i <= n; i++) {
int ans = 0;
for (int j = 0; j <= q; j++) ans += dp[i][j]; // ans统计答案
2 years ago
printf("%lld\n", ans);
}
}