POJ 2342 (树形DP)
生活随笔
收集整理的這篇文章主要介紹了
POJ 2342 (树形DP)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:?http://poj.org/problem?id=2342
題目大意:直屬上司和下屬出席聚會。下屬的上司出現了,下屬就不能參加,反之下屬參加。注意上司只是指直屬的上司。每個人出席的人都有一個快樂值,問最大的快樂值是多少。
解題思路:
首先確定一下頂頭上司是誰。
f[v]=u表示u是v的父親,這樣addedge完了之后,從1開始while(f[root]) root=f[root],最后root就是頂頭上司,也就是dfs的起點了。
用dp[i][0]表示對于第i個人不出席的最大快樂值,用dp[i][1]表示出席的最大快樂值。
則dp[i][0]=dp[i][0]+max(dp[son][0],dp[son][1]) ,原因是上司不出席,下屬可出席也可不出席,取個大的。
dp[i][1]=dp[i][1]+dp[son][0],原因是上司一旦出席,下屬絕對不能出席。
其中dp[i][1]的初始值為這個人的快樂值。
則ans=max(dp[root][0],dp[root][1])
?
注意本題的dfs只是起到推進樹結構作用,推完樹結構之后,還是傳統的DP轉移方式,不是記憶化搜索。
?
#include "cstdio" #include "vector" #include "cstring" using namespace std; #define maxn 6005 int hap[maxn],f[maxn],dp[maxn][2],head[maxn],tol; struct Edge {int to,next; }e[maxn]; void addedge(int u,int v) {e[tol].to=v;e[tol].next=head[u];head[u]=tol++; } void dfs(int root) {dp[root][1]=hap[root];for(int i=head[root];i!=-1;i=e[i].next) dfs(e[i].to);for(int i=head[root];i!=-1;i=e[i].next){dp[root][0]+=max(dp[e[i].to][1],dp[e[i].to][0]);dp[root][1]+=dp[e[i].to][0];} } int main() {//freopen("in.txt","r",stdin);int n,u,v;while(~scanf("%d",&n)&&n){memset(f,0,sizeof(f));memset(dp,0,sizeof(dp));memset(head,-1,sizeof(head));for(int i=1; i<=n; i++) scanf("%d",&hap[i]);for(int i=1; i<=n; i++){scanf("%d%d",&v,&u);if(u==0&&v==0) break;f[v]=u;addedge(u,v);}int root=1;tol=0;while(f[root]) root=f[root];dfs(root);int res=max(dp[root][0],dp[root][1]);printf("%d\n",res);} }?
| 13547096 | neopenx | 2342 | Accepted | 408K | 0MS | C++ | 1182B | 2014-10-20 12:18:43 |
總結
以上是生活随笔為你收集整理的POJ 2342 (树形DP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 寻找一个字符串中的最长不重复子串的长度
- 下一篇: JAVA之ArrayList集合