【codevs1380】没有上司的舞会

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])<<"
";
    return 0;
}
原文地址:https://www.cnblogs.com/gwj1314/p/9444793.html