#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=6010;
int happy[N];
bool has_father[N];
int dp[N][2];
int head[N],e[N],ne[N],idx;
void add(int x,int y){
e[idx]=y;
ne[idx]=head[x];
head[x]=idx;
idx++;
}
void dfs(int node){
dp[node][1]=happy[node];
for(int i=head[node];i!=-1;i=ne[i]){
dfs(e[i]);
dp[node][1]+=dp[e[i]][0];
dp[node][0]+=max(dp[e[i]][0],dp[e[i]][1]);
}
}
int main(){
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>happy[i];
}
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
add(b,a);
has_father[a]=true;
}
int gen=1;
while(has_father[gen]){
gen++;
}
dfs(gen);
cout<<max(dp[gen][0],dp[gen][1]);
return 0;
}
acwing.【没有上司的舞会】(树形dp)
于 2022-05-07 10:45:07 首次发布