HDU 1520 Anniversary party

树形DP

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;

const int maxn=6666;
int Ch[maxn];
int dp[maxn][2];
int n,u,v,node,tot;
vector<int> G[maxn];

void DFS(int x)
{
    for(int i=0; i<G[x].size(); i++)
    {
        DFS(G[x][i]);
        dp[x][1]+=dp[G[x][i]][0];
        dp[x][0]+=max(dp[G[x][i]][0],dp[G[x][i]][1]);
    }
}

int main()
{
    while(~scanf("%d",&n))
    {
        tot=0;
        memset(dp,0,sizeof(dp));
        for(int i=0; i<maxn; i++) G[i].clear();
        for(int i=1; i<=n; i++) scanf("%d",&dp[i][1]);
        while(1)
        {
            scanf("%d%d",&u,&v);
            if(u==0&&v==0) break;
            Ch[u]++;
            G[v].push_back(u);
        }
        for(int i=1; i<=n; i++) if(Ch[i]==0) node=i;
        DFS(node);
        printf("%d
",max(dp[node][1],dp[node][0]));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zufezzt/p/4698630.html