HDU 1520 Anniversary party 樹形DP,hduanniversary

來源:互聯網
上載者:User

HDU 1520 Anniversary party 樹形DP,hduanniversary

連結:http://acm.hdu.edu.cn/showproblem.php?pid=1520

題意:給出一個職場關係圖,每個人有自己的價值,並且每個人只有一個領導,我要邀請的人不可以是一個人和他的直系領導,問最多能邀請到多少價值的人。

思路:入門題,就是把簡單DP運用到了樹這種資料結構裡,蠻有趣的。看題意應該叫森林DP比較合適一點。首先是建樹,找到的根節點就是沒有父親節點的節點。對於樹上的一個節點u,dp[u][0]代表著不選擇這個節點能得到的最大價值,dp[u][1]代表著選擇這個節點能得到的最大價值。

狀態轉移方程:dp[u][0]=sum(max(dp[v][0],dp[v][1]))。不選當前節點,那麼他的每個子節點都是可以選也可以不選。

                            dp[u][1]=sum(dp[v][0])。選擇當前節點,那麼他的每個子節點都不可以選擇。

代碼:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<map>#include<queue>#include<stack>#include<vector>#include<ctype.h>#include<algorithm>#include<string>#define PI acos(-1.0)#define maxn 6005#define INF 0x7ffffffftypedef long long LL;using namespace std;int score[maxn],head[maxn],top,dp[maxn][2];bool from[maxn];void init(){    memset(head,-1,sizeof(head));    memset(from,0,sizeof(from));    memset(dp,0,sizeof(dp));    top=0;}struct Edge{    int v;    int next;} edge[maxn];int add_edge(int u,int v){    edge[top].v=v;    edge[top].next=head[u];    head[u]=top++;}void dfs(int u){    for(int i=head[u]; i!=-1; i=edge[i].next)    {        int v=edge[i].v;        dfs(v);        dp[u][1]+=dp[v][0];        dp[u][0]+=max(dp[v][1],dp[v][0]);    }    dp[u][1]+=score[u];}int main(){    int tot,u,v;    while(~scanf("%d",&tot))    {        init();        for(int i=1; i<=tot; i++)            scanf("%d",&score[i]);        while(scanf("%d%d",&u,&v))        {            if(u==0&&v==0)                break;            add_edge(v,u);            from[u]=true;        }        for(int i=1; i<=tot; i++)        {            if(!from[i])                dfs(i);        }        int ans=0;        for(int i=1; i<=tot; i++)        {            if(from[i]==0)                ans+=max(dp[i][0],dp[i][1]);        }        printf("%d\n",ans);    }    return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.