看成带有层次关系的一棵树
奇数层快乐指数加一起
偶数层快乐指数加一起
比较奇数层和偶数层的快乐指数,取最大
(因为职员与直系上司不能同时存在)
#include<iostream>
using namespace std;
const int N = 6e3+10;
int f[N];
int count[N]={0};
int happy[N]={0};
int maxn=0;
int find(int x){
int root = x;
int num=1;
while(f[root] != root){
root = f[root];
num++;
}
count[x] = num;
return root;
}
int main(){
int n,l,k;
cin>>n;
for(int i=1;i<=n;i++){
f[i] = i;
}
for(int i=1; i <= n; i++){
cin>>happy[i];
}
for(int i=0;i<n-1;i++){
cin>>l>>k;
f[l] = k;
}
int r=0;
for(int i=1;i<=n;i++){
find(i);
}
int x=0,y=0;
for(int i=1;i<=n;i++){
if(happy[i]>0){
if(count[i]%2==0){
x += happy[i];
}
else{
y += happy[i];
}
}
}
cout<<max(x,y)<<endl;
}