【codevs1380】沒有上司的舞會
阿新 • • 發佈:2019-02-13
problem
solution
codes
/*
用f[x][0],f[x][1] 分別表示x沒去和去了的最大價值。
f[x][0] = sigmar:max(f[y][0],f[y][1]);
f[x][1] = sigmar:f[y][0];
*/
#include<iostream>
#include<algorithm>
#include<vector>
#define maxn 6000*2
using namespace std;
int n, r[maxn], f[maxn][2], in[maxn];
vector<int>G[maxn];
void dp(int x){
f[x][1] = r[x];
for(int i = 0; i < G[x].size(); i++){
int y = G[x][i];
dp(y);
f[x][0] += max(f[y][0],f[y][1]);
f[x][1] += f[y][0];
}
}
int main(){
cin>>n;
for(int i = 1; i <= n; i++)cin>>r[i];
for(int i = 1; i <= n; i++){
int a, b; cin>>a>>b;
G[b].push_back(a);
in[a]++;
}
int head = 0; //找樹根,即入度為0的結點
for(int i = 1; i <= n; i++)
if(in[i]==0){ head = i; break; }
dp(head);
cout<<max(f[head][1],f[head][0])<<"\n";
return 0;
}