我是靠谱客的博主 忧虑钢铁侠,最近开发中收集的这篇文章主要介绍树形dp(校园聚会),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

HDU - 1520


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


题意:先输入N,再输入N个员工的欢乐度,接下来输入员工之间的上下级关系,上下级不能同时参加这个聚会,问如何选人使得欢乐度最高,输出欢乐度。

思路:先建树,用链式前向星添边,找出入度为零的点作为根节点,再dfs求dp,状态转移方程,如果当前点不取,dp为max(下级取,下级不取),如果当前点取,dp为下级点都不取并加上自己的欢乐度。


代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#include<cstring>
int N;
int a[6666];
int dp[6666][2];
#define MAX 6666
struct node
{
    int to,nex;
}edge[MAX*2+5];
int head[MAX+5],cnt;
void add(int u,int v)
{
    edge[cnt].to=v;
    edge[cnt].nex=head[u];
    head[u]=cnt++;
}
int rudu[6666];

void dfs(int root)
{
	for(int i=head[root]; ~i; i=edge[i].nex)
	{
		dfs(edge[i].to);
	}
	dp[root][0]=0;
	dp[root][1]=a[root];
	for(int i= head[root]; ~i; i=edge[i].nex)
	{
		dp[root][0]+=max(dp[edge[i].to][1], dp[edge[i].to][0]);
		dp[root][1]+=dp[edge[i].to][0];
	}
}


int main()
{ 
	while(~scanf("%d", &N))
	{
		int i;
		for(i=1;i<=N;i++)
		{
			scanf("%d",&a[i]);
		}
		int x,y,root;
		memset(head,-1,sizeof(head));
		memset(rudu,0,sizeof(rudu));
	    cnt=0;//³õʼ»¯ 0
		while(scanf("%d%d",&x,&y),x&&y)
		{
			add(y, x);
			rudu[x]++;
		}
		for(i = 1; i <= N; i++) 
		if(!rudu[i]) root=i;
		dfs(root);
		printf("%dn", max(dp[root][0], dp[root][1]));
	}
	return 0;
} 


最后

以上就是忧虑钢铁侠为你收集整理的树形dp(校园聚会)的全部内容,希望文章能够帮你解决树形dp(校园聚会)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(28)

评论列表共有 0 条评论

立即
投稿
返回
顶部