【树形DP】最大利润

传送门

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

Source
Ural State University Internal Contest October’2000 Students Session


题目大意

每个员工都有一个上司,在晚会上每个人都不希望有自己的上司在场,每个人都有一个参加晚会幸福值
找到一份合适的名单,使幸福值和最高


解题思路

纠结了老半天怎么判环,才发现题目是不可能有环的w(゚Д゚)w

树形DP
y x [ i ] yx[i] yx[i]为第 i i i个人要参加晚会,设 b x [ i ] bx[i] bx[i]为第 i i i个人不参加晚会
如果 i i i参加晚会,那么 i i i的下属不能参加晚会

yx[x]+=bx[y];

如果 i i i不参加晚会,那么 i i i的下属可参加可不参加晚会,去幸福值最大的那个

bx[x]+=max(yx[y],bx[y]);

注意
因为不知道校长(顶头上司,就是根)是哪个
所以选哪个点为起始点都可,程序里选的是第1个点


Code

#include<iostream>
#include<cstdio>
using namespace std;
struct DT{
	int y,next;
}a[150000];
int n,x,y,num,head[65000],bx[65000],yx[65000];
void add(int x,int y){
	a[++num].y=y,a[num].next=head[x],head[x]=num;
}
void dfs(int x,int fa){
	for(int i=head[x];i;i=a[i].next){
		int y=a[i].y;
		if(y==fa)continue;//判断有没有走回去
		dfs(y,x);
		bx[x]+=max(yx[y],bx[y]);
		yx[x]+=bx[y];
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	    scanf("%d",&yx[i]);
	for(int i=1;i<=n;i++){
		scanf("%d%d",&x,&y);
		add(x,y);add(y,x);//邻接表
	}
	dfs(1,1);
	printf("%d",max(bx[1],yx[1]));//答案也要取max
}

你可能感兴趣的:(树形DP,DP)