HDU 1520 Anniversary party (樹形DP)

題面

題意:一個派對裏有n個人,n個人之間有着一張上下級關係圖,派對要求上級和下級不能同時出現,而每個人都有一個rating值,要求選擇哪些人到場能使rating值之和最大

 

思路:

1.每個人有兩種狀態-出席或不出席

2.上級出席那麼其直接對應的下級不能出席,下級出席則其直接對應的上級不能出席

代碼:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
const int N=1e4+5;
struct E
{
    int val;
    int next;
} edge[5*N+10];
int head[N],vis[N],c,dp[N][2],con[N];
int selMax(int x,int y)
{
    return x>=y?x:y;
}
void add(int x,int y)
{
    edge[c].val=y;
    edge[c].next=head[x];
    head[x]=c;
    c+=1;
}
void DFS(int root)
{
    dp[root][1]=con[root];
    dp[root][0]=0;
    vis[root]=1;
    for(int i=head[root]; i!=-1; i=edge[i].next)
    {
        int cur=edge[i].val;
        if(!vis[cur])
        {
            DFS(cur);
            dp[root][1]+=dp[cur][0];
            dp[root][0]+=selMax(dp[cur][1],dp[cur][0]);
        }
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        for(int i=1; i<=n; i+=1){
            scanf("%d",&con[i]);
        }
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
        memset(dp,0,sizeof(dp));
        int u,v;
        c=0;
        while(true)
        {
            scanf("%d%d",&u,&v);
            if(u+v==0)
                break;
            add(v,u);
            add(u,v);
        }
        DFS(1);
        printf("%d\n",selMax(dp[1][0],dp[1][1]));
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章