Ural1039 (树形dp入门)

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 ratingof the guests.

Sample

inputoutput
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
5

和poj上的树形dp入门的题是一样的,经典入门题。
题意就是开一个party,每个员工都有一个欢乐值,只有是上司和下属不同时存在时才能欢乐,问怎样安排能有最大的欢乐值。
 本质上就是有一棵树,每个节点都有一个权值,父亲和儿子节点不能同时存在,问怎样选这样的集合使权值最大。那么每个人只有去和不去两种状态   dp[i][0]表示i不去,dp[i][1]表示i去,状态转移方程就是dp[i][0]=sigma(max(dp[j][0],dp[j][1])),dp[i][1]=sigma(dp[j][0]) j为i的孩子结点。

//分类:dp 每个人只有去和不去两种状态,其实搜索也就可以了,但是效率太差
// dp[i][0]表示i不去的欢乐值,dp[i][1]表示i去的欢乐值
//  
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define N 6666
int n;
int a[N];
int fa[N];
int dp[N][2];
bool vis[N];
vector<int> g[N*4];
//还是dfs .. 
void dfs(int u)
{
	int i,j;
	dp[u][0]=0;dp[u][1]=a[u];
    //cout<<dp[u][0]<<" * "<<dp[u][1]<<endl;
	for(i=0;i<g[u].size();i++)
	{
		int v=g[u][i];
		dfs(v);   //自底向上的计算  
		dp[u][0]+=max(dp[v][0],dp[v][1]);
		dp[u][1]+=dp[v][0];
		
	}
	
}
int main()
{
//	freopen("q.in","r",stdin);
	int n;
	int i,j;
	int l,k,root;
	memset(fa,0,sizeof(fa));
	memset(dp,0,sizeof(dp));
	scanf("%d",&n);
	for(i=1;i<=n;i++)scanf("%d",&a[i]);
	
	while(~scanf("%d%d",&l,&k) && l+k)
	{
		g[k].push_back(l);
		fa[l]=k;		
	}
	for(i=1;i<=n;i++)if(fa[i]==0){root=i;break;}
	//cout<<root<<endl;
    dfs(root);
     cout<<max(dp[root][0],dp[root][1])<<endl;
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值