题目链接:http://poj.org/problem?id=2342
Description
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
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[i][0]为第i号人不去的情况下,以其为根的子树,最大的rating和;dp[i][1]为第i号人去的情况下,以其为根的子树,最大的rating和;
对于树上的每条边:edge[u][ (v[1]) ]……edge[u][ (v[k]) ]……,都有:
dp[u][0]+=∑ max( dp[ (v[k]) ][1] , dp[ (v[k]) ][0] )
dp[u][1]+=∑ dp[ (v[k]) ][0]
将每个人的dp[i][1]按照输入初始化后,用vector记录下一个点的所有孩子,并且找到root,最后进行DFS即可。
1 #include<cstdio> 2 #include<cstring> 3 #include<vector> 4 #include<algorithm> 5 #define MAXN 6005 6 using namespace std; 7 int n,fl[MAXN],dp[MAXN][2],root; 8 vector<int> child[MAXN]; 9 void dfs(int now) 10 { 11 int next; 12 for(int i=0;i<child[now].size();i++) 13 { 14 next=child[now][i]; 15 dfs(next); 16 dp[now][0]+=max(dp[next][1],dp[next][0]); 17 dp[now][1]+=dp[next][0]; 18 } 19 } 20 int main() 21 { 22 memset(fl,0,sizeof(fl)); 23 24 scanf("%d%",&n); 25 26 for(int i=1;i<=n;i++) scanf("%d",&dp[i][1]); 27 for(int i=1;i<=n;i++) 28 { 29 int L,K; 30 scanf("%d%d",&L,&K); 31 child[K].push_back(L); 32 fl[L]=1; 33 } 34 for(int i=1;i<=n;i++) if(fl[i]==0){root=i;break;} 35 36 dfs(root); 37 printf("%d ",max(dp[root][0],dp[root][1])); 38 }