树形DP Anniversary party (hdu1520)

最简单的树形DP

先找到根节点

从上往下dfs

dp[f][0] +=max(dp[g[f][i]][1],dp[g[f][i]][0]);
dp[f][1]+=dp[g[f][i]][0];

#include <bits/stdc++.h>
using namespace std;
const int N=100000;
int father[N];
int dp[N][2];
vector <int>g[N];
void dfs(int f)
{
    for(int i=0; i<g[f].size(); i++)
    {

        dfs(g[f][i]);
        dp[f][0] +=max(dp[g[f][i]][1],dp[g[f][i]][0]);
        dp[f][1]+=dp[g[f][i]][0];

    }
}
int main()
{
    for(int i=0; i<N; i++)
        father[i]=-1;
    int n;
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>dp[i][1];
    }
    while(1)
    {
        int a,b;
        cin>>a>>b;
        if(a==b&&b==0)
            break;
        father[a]=b;
        g[b].push_back(a);
    }
    int root=1;
    while(father[root]!=-1)
    {
        root=father[root];
    }
    dfs(root);
    cout<<max(dp[root][0],dp[root][1]);
    return 0;
}
发布了19 篇原创文章 · 获赞 3 · 访问量 1392

猜你喜欢

转载自blog.csdn.net/xuanhuangwendao/article/details/81215369