描述
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.
输入
Multiple cases, for each case:
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. each case is ended with the line
0 0
输出
For each case, output should contain the maximal sum of guests’ ratings.
样例输入
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
样例输出
5
题意
每个点有一个权值,给你几个点之间的关系 L K,点L的上司是K点。
你需要选出一些点,选中的点中不能有直属的上司和下属关系,要你输出这些选中的点的和最大的值
我们从根节点出发来选取点。定义dp[i][0]表示不选中这个点时的最优解,dp[i][1]表示选中这个点时的最优解。
那么我们能得出这个点的值是由它的下属来决定的
dp[k][1]+=dp[u][0];//选择这个点,那么它的下属就不能选择
dp[k][0]+=max(dp[u][0],dp[u][1]);//不选择这个点那么它的下属可选可不选
最后我们还需要判断一下你的根节点是否要选取
#include <bits/stdc++.h>
using namespace std;
const int N=6005;
vector<int>G[N];
int vis[N],dp[N][2],fa[N];
int n,x,y;
void f(int k){
vis[k]=1;
int num=G[k].size();
for(int i=0;i<num;i++){
if(vis[G[k][i]]==0){
f(G[k][i]);
dp[k][1]+=dp[G[k][i]][0];
dp[k][0]+=max(dp[G[k][i]][0],dp[G[k][i]][1]);
}
}
}
int gen(int x){
if(x==fa[x]) return x;
return fa[x]=gen(fa[x]);
}
int main()
{
while(~scanf("%d",&n)){
for(int i=0;i<=n;i++) G[i].clear();
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++){
dp[i][0]=0;
fa[i]=i;
scanf("%d",&dp[i][1]);
}
while(scanf("%d%d",&x,&y),x||y){
G[y].push_back(x);
int xx=gen(x),yy=gen(y);
if(xx!=yy){
fa[xx]=yy;
}
}
int tt;
for(int i=1;i<=n;i++){
if(fa[i]==i){
tt=i;
break;
}
}
f(tt);
printf("%d\n",max(dp[tt][0],dp[tt][1]));
}
return 0;
}