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.

46 lines
984 B

#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
vector<int> g[N]; // 邻接表,一个正图,一个反图
int c[N]; // 每个树洞中松鼠的数量
/*
测试用例
4
5
3
6
1
1 2
1 3
2 4
2
*/
int dfs(int u, int fa, int k) {
if (k == 0) return c[u];
int sum = c[u];
for (int i = 0; i < g[u].size(); i++) {
if (g[u][i] == fa) continue;
sum += dfs(g[u][i], u, k - 1);
}
return sum;
}
int main() {
int n; // 树洞的数量
cin >> n;
for (int i = 1; i <= n; i++) cin >> c[i]; // 每个树洞中松鼠的数量
for (int i = 1; i < n; i++) {
int a, b; // 表示两个树洞相连接
cin >> a >> b;
g[a].push_back(b); // 用邻接表保存一下某个树洞与哪两个其它树洞相连接
g[b].push_back(a);
}
int k;
cin >> k;
for (int i = 1; i <= n; i++)
cout << dfs(i, -1, k) << endl;
return 0;
}