现在的位置: 首页 > 综合 > 正文

hdu1520

2013年01月30日 ⁄ 综合 ⁄ 共 2380字 ⁄ 字号 评论关闭

Anniversary party

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3222    Accepted Submission(s): 1471

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:
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
 

Source
 

此题保证主管与员工的关系形成一棵树,每人都有一个愉快值,主管与他的直接员工不能同时参加,要求找到这样的最大组合;

题目抽象为在一棵树上选择若干不互相关联的带权顶点,总的权值最大,是个比较裸的树状DP

状态转移方程:
对于叶子节点 dp[k][0] = 0, dp[k][1] = Hap[i]
对于非叶子节点i,
dp[i][0] +=max(dp[j][0], dp[j][1]) (j是i的儿子)
dp[i][1] + =dp[j][0] (j是i的儿子)
最大愉快值即为max(dp[root][0], dp[root][1])

 

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


const int MAXN=6000+50;
//bool IsRoot[MAXN];可以用来加速par[MAXN]代替来加速
int par[MAXN];//存放该节点的父亲节点
int Hap[MAXN];//存放节点的权值
vector<int>g[MAXN];//存放无向图
int dp[MAXN][2];//dp[i][0]表示不选该节点,dp[i][1]表示选该节点

int Max(int a,int b)
{
	return a<b?b:a;
}

void Dfs(int root)
{
	int i,ch_n;
	ch_n=g[root].size();
	dp[root][0]=0,dp[root][1]=Hap[root];
	for(i=0;i<ch_n;i++)
		Dfs(g[root][i]);

	for(i=0;i<ch_n;i++)
	{
		dp[root][0]+=Max(dp[g[root][i]][0],dp[g[root][i]][1]);
		dp[root][1]+=dp[g[root][i]][0];
	}
}

int main()
{
	int i,n,a,b;
	while(~scanf("%d",&n))
	{
		for(i=1;i<=n;i++)
		{
			scanf("%d",&Hap[i]);
			g[i].clear();
			//IsRoot[i]=true;
			par[i]=-1;
			dp[i][0]=dp[i][1]=0;
		}
		while(scanf("%d%d",&a,&b))
		{
			if(0==a&&0==b)
				break;
			g[b].push_back(a);
		//	IsRoot[a]=false;
			par[a]=b;
		}

		i=1;
		while(par[i]!=-1)//(!IsRoot[i])
			i=par[i];//i++;
		Dfs(i);
		printf("%d\n",Max(dp[i][0],dp[i][1]));
	}
	return 0;
}

 

 

抱歉!评论已关闭.