AcWing 1220. 生命之树
原题链接
中等
作者:
wjie
,
2020-07-04 22:41:50
,
所有人可见
,
阅读 582
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long LL;
const int N = 1e5 + 5;
vector<int> G[N];
int w[N];
LL dfs(int u, int father)
{
LL res = w[u];
for (int i = 0; i < G[u].size(); ++i)
{
int v = G[u][i];
if (v == father)
continue;
LL tmp = dfs(v, u);
if (tmp > 0)
res += tmp;
}
return res;
}
int main()
{
int n, root = 1;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
{
scanf("%d", &w[i]);
if (w[root] < w[i])
root = i;
}
for (int i = 0; i < n-1; ++i)
{
int u, v;
scanf("%d %d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
printf("%lld", dfs(root, -1));
return 0;
}