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 T 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 0Sample Output
5
题意:每一人都有自己的权重,下属不能和自己的直接上司一块去,那么上司去的时候 ,全部的直接下属都不能去;上司不去下属可以去也可以不去。
因为自己对dp的了解不深,所以就不分析原理了,这个是AC的代码
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
#include<cstring>
#define maxn 6010
using namespace std;
vector <int>g[maxn];//上司和下属的关系就处理好了 类似邻接表
int dp[maxn][2];//0 代表不去 1 代表去
int n,rat[maxn],deg[maxn];//deg入度 如果一个人没有上司 那么就是根
//N 1 6000 -128 127 有可能一个上司会有好多个下属 并不是二叉树
void dfs(int root);
int main()
{
int l,k;
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
g[i].clear();//这个是把它里面含有的点给清空
cin>>rat[i];//这个就是把权重给读进来了
}
memset(deg,0,sizeof(deg));//这个是把入度给清空
while(cin>>l>>k && l!=0){
g[k].push_back(l);
deg[l]++;
}
for(int i=1;i<=n;i++){
if(deg[i]==0){
dfs(i);//如果是根的话
int ans = max(dp[i][0],dp[i][1]);//去还是不去
cout<<ans<<endl;
break;
}
}
}
return 0;
}
void dfs(int root)
{
int sum1 = 0;
int sum2 = 0;
for(int i=0;i<g[root].size();i++){//看这个上司的全部下属
int v = g[root][i];
dfs(v);
sum1 += max(dp[v][0],dp[v][1]);//上司不去
sum2 += dp[v][0];//sum2 是上司去
}
dp[root][0] = sum1;
dp[root][1] = sum2 + rat[root];//上司去
// printf("dp[%d][0] = %d, dp[%d][1] = %d\n",root,dp[root][0],root,dp[root][1]);
}