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
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[v][1]和dp[v][0]表示该情况下其子树的最大权值;
初始化时 dp[v][0]=0;dp[v][1]=weight;
状态转移方程:dp[v][0]+=max(dp[u][1],dp[u][0]); (职员v不参加,考虑其下属u要不要参加)
dp[v][1]+=dp[u][0]; (职员v参加,其所有下属一定都不参加)
最后结果为max(dp[root][0],dp[root][1])。
father数组记录各节点的父节点,用于最后查找根节点。容器数组G记录各点的子节点。
#include<iostream>
#include<vector>
using namespace std;
const int maxn=6005;
int father[maxn],dp[maxn][2];
vector<int> G[maxn];
void dfs(int v)
{
for(int i=0;i<G[v].size();i++)
{
int u=G[v][i];
dfs(u);
dp[v][0]+=max(dp[u][0],dp[u][1]);
dp[v][1]+=dp[u][0];
}
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d",&dp[i][1]);
}
int l,k;
while(cin>>l>>k)
{
if(l==0&&k==0)
break;
G[k].push_back(l);
father[l]=k;
}
int root=1;
while(father[root]!=0) root=father[root];
dfs(root);
cout<<max(dp[root][0],dp[root][1]);
return 0;
}