HDU1520 Anniversary party【Tree DP】

Topic link: HDU1520 Anniversary party

Question: Give you a tree, each point has value, father and son cannot choose at the same time, ask the maximum value of the selected point;

Analysis: Find the root, then go down the DFS tree DP, update the parent node from the child nodes, dp[i][1] means choose i, dp[i][0] means not choose i, and then update the parent node backwards;

#include<bits/stdc++.h>
#define pb push_back
using namespace std;
const int maxn=6007;
vector<int> g[maxn];
int a[maxn],dp[maxn][2],ind[maxn];
int n,x,y,rt;
void dfs(int x)
{
    dp[x][1]=a[x];dp[x][0]=0;
    for(auto y:g[x])
    {
        dfs(y);
        dp[x][1]+=dp[y][0];
        dp[x][0]+=max(dp[y][1],dp[y][0]);
    }
}
void rua()
{
    memset(ind,0,sizeof(ind));
    for(int i=1;i<=n;i++) scanf("%d",&a[i]),g[i].clear();
    while(~scanf("%d%d",&x,&y) && x && y) g[y].pb(x),ind[x]++; 
    for(int i=1;i<=n;i++) if(!ind[i]) rt=i;
    dfs(rt);
    printf("%d\n",max(dp[rt][0],dp[rt][1]));
}
int main()
{
    while(~scanf("%d",&n)) rua();
    return 0;
}

 

Guess you like

Origin blog.csdn.net/qq_43813163/article/details/102605593