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
题意:
现在有个聚会,告诉你n个人,各自的价值,并且告诉一些人的主管从属关系,比如L K表示后者K是前者L的上司。现在有个问题,如果聚会中两个人是直接上司下属关系那么就会很尴尬,问在不发生尴尬的情况聚会最大价值。
分析:
树形DP。
代码:
#include <stdio.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 6010;
int data[maxn],ft[maxn],nt[maxn],v[maxn],tot;
int vis[maxn];
int dp[maxn][2];
void dfs(int now)
{
dp[now][0] = 0;
dp[now][1] = v[now];
for(int i = ft[now] ; i != -1 ; i = nt[i])
{
dfs(data[i]);
}
for(int i = ft[now] ; i != -1 ; i = nt[i])
{
dp[now][1] += dp[data[i]][0];
dp[now][0] += max(dp[data[i]][0],dp[data[i]][1]);
}
}
int main()
{
int t,n,u;
while(~scanf("%d",&n))
{
for(int i = 1 ; i <= n ; i ++)
scanf("%d",&v[i]);
tot = 0;
memset(ft,-1,sizeof(ft));
memset(vis,0,sizeof(vis));
memset(dp,0,sizeof(dp));
for(int i = 0 ; i < n ; i ++)
{
scanf("%d%d",&t,&u);
if(u == 0 && t == 0) break;
data[tot] = t;
nt[tot] = ft[u];
ft[u] = tot++;
vis[t] = 1;
}
int f = -1;
for(int i = 1 ; i <= n ; i ++)
if(!vis[i])
{
f = i;
break;
}
dfs(f);
printf("%d\n",max(dp[f][0],dp[f][1]));
}
return 0;
}