Anniversary party
Time Limit: 1000MS
Memory Limit: 65536K
Total Submissions: 6184
Accepted: 3563
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、
1、反向建图,找度为0的节点,那么就是最高的官,我们设定它为根节点,我们从它开始在树上动态规划。
2、
我们设定dp【i】【0】表示节点i属于被邀请的一个人,其子节点问题全部解决了的情况下的最大开心值。
我们设定dp【i】【1】表示节点i不属于被邀请的一个人,其子节点问题全部解决了的情况下的最大开心值。
那么不难理解,max(dp【root】【0】,dp【root】【1】)就是我们要求的解。
3、
其中动态转移方程写出的思路:
u是i的子节点。
dp【i】【0】=val【i】+sum(节点i的子节点)dp【u】【1】;这里不难理解:因为节点i属于被邀请的一个人,那么其直接相连的子节点就是其当前节点的直接上下级关系,是不能够被邀请的。
dp【i】【1】=sum(节点i的子节点)max(dp【u】【1】,dp【u】【0】);因为点i不属于被邀请的一个人,那么其相连的子节点虽然与当前节点为直接上下级关系,但是其因为当前i节点已经保证不属于被邀请的一个人了,所以其子节点的状态无所厚非,直接选其中最优的即可。
AC代码
#include<stdio.h>
#include<string.h>
#include<vector>
using namespace std;
//反向建图,找入度为0的点。
int dp[10000][2];
int degree[10000];
int val[10000];
vector<int >mp[10000];
int vis[10000];
void DP(int now)
{
dp[now][0]=val[now];
dp[now][1]=0;
vis[now]=1;
for(int i=0;i<mp[now].size();i++)
{
int to=mp[now][i];
if(vis[to]==1)continue;
DP(to);
dp[now][0]+=dp[to][1];
dp[now][1]+=max(dp[to][1],dp[to][0]);
}
}
int main()
{
int n,root;
scanf("%d",&n);
for(int i=1;i<=n;i++)vis[i]=0;
for(int i=1;i<=n;i++)degree[i]=0;
for(int i=1;i<=n;i++)mp[i].clear();
for(int i=1;i<=n;i++)scanf("%d",&val[i]);
while(1)
{
int x,y;
scanf("%d%d",&x,&y);
if(x==0&&y==0)
{
break;
}
mp[y].push_back(x);
degree[x]++;
}
for(int i=1;i<=n;i++)
{
if(degree[i]==0)
{
root=i;
break;
}
}
DP(root);
printf("%d\n",max(dp[root][0],dp[root][1]));
}