POJ(2342) Anniversary party(树dp)

POJ(2342) Anniversary party(树dp)

There is going to be a party to celebrate the 80-th Anniversary of the Ural State University. The University has a hierarchical structure of employees. It means that the supervisor relation forms a tree rooted at the rector V. E. Tretyakov. In order to make the party funny for every one, the rector does not want both an employee and his or her immediate supervisor to be present. The personnel office has evaluated conviviality of each employee, so everyone has some number (rating) attached to him or her. Your task is to make a list of guests with the maximal possible sum of guests’ conviviality ratings.
Input

Employees are numbered from 1 to N. A first line of input contains a number N. 1 <= N <= 6 000. Each of the subsequent N lines contains the conviviality rating of the corresponding employee. Conviviality rating is an integer number in a range from -128 to 127. After that go N – 1 lines that describe a supervisor relation tree. Each line of the tree specification has the form:
L K
It means that the K-th employee is an immediate supervisor of the L-th employee. Input is ended with the line
0 0
Output

Output should contain the maximal sum of guests’ ratings.
Sample Input

7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
Sample Output

5
题意: 一棵树,每个节点有权值,儿子父亲不能同时取,求解从树上选取点能获得的最大权值。

刚接触树dp 这应该算是树dp里比较简单的题;
dp[i][0] 表示不取该节点 其子树内取得的最大权值和.
dp[i][1] 表示取该节点 其子树内取得的最大权值和.

根据题意 可以知道 (j为i的子节点)
dp[i][0] 可以由 两个状态转移过来 dp[j][0],和dp[j][1].(即取子节点和不取子节点都是可行的)
dp[i][1] 只能由一种状态即dp[j][0] 转移过来;
可以得到转移方程:
dp[i][0]=Σmax(dp[j][0],dp[j][1])
dp[i][1]=a[i]+Σdp[j][0]
最后输出两者中较大的那个即可;
代码:


#include<iostream>
#include<cstdio>
#include<map>
#include<math.h>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+7;
struct node {
     int next,to;
}e[maxn];
int num=0,a[maxn],dp[maxn][2],head[maxn],s[maxn];
void add(int u,int v){   //建树
    e[num].next=head[u];
    e[num].to=v;
    head[u]=num++;
}
void dfs(int u,int v){
     dp[u][1]=a[u];
     for(int i=head[u];i!=-1;i=e[i].next){
        int to=e[i].to;
        dfs(to,u);
        dp[u][0]+=max(dp[to][0],dp[to][1]);
        dp[u][1]+=dp[to][0];
     }
}
int main (){
    int n,root,u,v;
    cin>>n;
    memset(head,-1,sizeof(head));
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<n;i++){
        scanf("%d%d",&u,&v);
        add(v,u);
        s[u]++;
    }
    scanf("%d%d",&u,&v);
    for(int i=1;i<=n;i++){       //找根节点
        if(s[i]==0){
         root=i;
         break;
        }
    }
    dfs(root,-1);
    printf ("%d\n",max(dp[root][0],dp[root][1]));

}
发布了11 篇原创文章 · 获赞 1 · 访问量 397

猜你喜欢

转载自blog.csdn.net/hddddh/article/details/104704263