P1352树形dp
作者:
多米尼克領主的致意
,
2024-06-04 18:56:21
,
所有人可见
,
阅读 5
#include <bits/stdc++.h>
using namespace std;
const int N = 6e3 + 10;
int r[N], fa[N];
vector<int>e[N];
int dp[N][2];
int n;
void dfs(int u){
dp[u][1] = r[u];
dp[u][0] = 0;
for(int i = 0;i < e[u].size();i++){
int v = e[u][i];
dfs(v);
dp[u][1] += dp[v][0];
dp[u][0] += max(dp[v][1], dp[v][0]);
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 1;i <= n;i++)cin >> r[i];
for(int i = 1;i < n;i++){
int x, y;
cin >> x >> y;
e[y].push_back(x);
fa[x] = y;
}
int t = 1;
while(fa[t])t = fa[t];
dfs(t);
cout << max(dp[t][0], dp[t][1]) << endl;
return 0;
}