Anniversary partyTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 18069 Accepted Submission(s): 6792 Problem 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 T lines that describe a supervisor relation tree. Each line of the tree specification has the form:
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
Source Ural State University Internal Contest October'2000 Students Session |
题意:有一颗上司与下属的树,现在安排若干个人出席一个聚会,每一个人都有一个快乐值(参加聚会当然快乐啊),现在要让聚会的氛围最快乐,要求下属和它的直系上司不能同时参加,求整个聚会的最大的快乐值。
思路:树形dp,职工表就是一颗树,对与上司来讲,上司如果参加聚会,他的下属就不能参加;上司如果不参加参加聚会,他的下属参不参加都可以。我使用一个二位数组dp[2][MAXN];设变量u为上司,数组v是他的下属。状态转移方程为:
dp[1][u]+=dp[0][v[i]]; 上司不参见聚会
dp[0][u]+=max(dp[1][v[i]],dp[0][v[i]]); 上司参加聚会
从root根部遍历,dfs利用递归的回溯,找到下属的快乐值,就能更新当前上司的快乐值了。
AC代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 6000+10;
int a[MAXN],dp[2][MAXN],head[MAXN],f[MAXN];
int cnt;
struct Edge{
int next,to,w;
}edge[MAXN<<1];
void add(int u,int v,int w){
edge[cnt]=(Edge){head[u],v,w};
head[u]=cnt++;
}
void dfs(int x){
dp[1][x]=a[x];
for(int i=head[x];~i;i=edge[i].next){
int son=edge[i].to;
dfs(son);
dp[0][x]+=max(dp[0][son],dp[1][son]);
dp[1][x]+=dp[0][son];
}
}
int main(){
int n;
while(~scanf("%d",&n)){
cnt=0;
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
memset(f,-1,sizeof(f));
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
int u,v;
while(scanf("%d%d",&v,&u),(u||v)){
add(u,v,a[v]);
f[v]=u;
}
int root=1;
while(f[root]!=-1){
root=f[root];
}
dfs(root);
printf("%d\n",max(dp[1][root],dp[0][root]));
}
return 0;
}