1039. Anniversary Party

1039. Anniversary Party

Time limit: 0.5 second
Memory limit: 8 MB

Background

The president of the Ural State University is going to make an 80'th Anniversary party. The university has a hierarchical structure of employees; that is, the supervisor relation forms a tree rooted at the president. Employees are numbered by integer numbers in a range from 1 to  N, The personnel office has ranked each employee with a conviviality rating. In order to make the party fun for all attendees, the president does not want both an employee and his or her immediate supervisor to attend.

Problem

Your task is to make up a guest list with the maximal conviviality rating of the guests.

Input

The first line of the input contains a number  N. 1 ≤  N ≤ 6000. 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 the supervisor relation tree goes. Each line of the tree specification has the form
<L> <K>
which means that the  K-th employee is an immediate supervisor of  L-th employee. Input is ended with the line
0 0

Output

The output should contain the maximal total rating of the guests.

Sample

input output
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
5


简单树形dp,dp[i][0]表示以i为根的子树,不取i的最优值,dp[i][1]表示以i为根的子树,取i的最优值。
这里Conviviality rating可为负数,但实际上最优解中不可能有取负数对应的那个人。
因此,修改dp[i][1]的定义,如果i的Conviviality rating为正数,则加上Conviviality rating,否则加上0.
这样做相当于不取i,那么显然dp[i][1]<=dp[i][0],这样转移时会从dp[i][0]转移出去,所以这样的修改是可以得到最优值的,但这样做的好处是dp数组可以初始化为0。

代码:
<pre name="code" class="cpp">#include<cstdio>
#include<iostream>
#include<cstring>
#define Maxn 6010
using namespace std;

int v[Maxn],head[Maxn],nxt[Maxn*10],fa[Maxn],id[Maxn*10],dp[Maxn][2];
int tot=0;
int dfs(int x,int d){
    int &ans=dp[x][d];
    if(ans) return ans;
    if(d==1) ans=max(ans,v[x]);
    if(head[x]==-1) return d?max(0,v[x]):0;
    for(int i=head[x];i!=-1;i=nxt[i])
        if(d==1) ans+=dfs(id[i],0);
        else if(dfs(id[i],1)>dfs(id[i],0)) ans+=dp[id[i]][1];
        else ans+=dp[id[i]][0];
    return ans;
}
int main()
{
    int n,a,b;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",v+i);
    memset(fa,-1,sizeof fa);
    memset(head,-1,sizeof head);
    memset(dp,0,sizeof dp);
    while(scanf("%d%d",&a,&b),a){
        fa[a]=b;
        nxt[tot]=head[b];
        head[b]=tot;
        id[tot++]=a;
    }
    int ans=0;
    for(int i=1;i<=n;i++)
        if(fa[i]==-1) ans+=dfs(i,0)>dfs(i,1)?dp[i][0]:dp[i][1];
    printf("%d\n",ans);
	return 0;
}

 
 

你可能感兴趣的:(1039. Anniversary Party)