1. 程式人生 > >HDU 1520 Anniversary party (樹形dp)

HDU 1520 Anniversary party (樹形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 
題目大意:給你一 棵關係樹,讓你從中選擇若干個人,這些人之間不能有直接的上下級關係,要求最後的到的權值最大

任何一個點的取捨可以看作一種決策,那麼狀態就是在某個點取的時候或者不取的時候,以他為根的子樹能有的最大活躍總值。分別可以用f[i,1]和f[i,0]表示第i個人來和不來。

當i來的時候,dp[i][1] += dp[j][0];//j為i的下屬

當i不來的時候,dp[i][0] +=max(dp[j][1],dp[j][0]);//j為i的下屬

#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
using namespace std;
int dp[6005][2],a[6005],f[6005];//f用於查詢根節點 
vector<int> e[6005];//存樹 
void dfs(int t)
{
	dp[t][1]=a[t];
	for(int i=0;i<e[t].size();i++)
	{
		int son=e[t][i];
		dfs(son);//以子節點為根節點進行搜尋 
		dp[t][0]+=max(dp[son][0],dp[son][1]);//狀態轉換 
		dp[t][1]+=dp[son][0];		
	}
}
int main()
{
	int n,i,j,k;
	int b,c;
	int t;
	while(cin>>n)
	{
		memset(dp,0,sizeof(dp));
		for(i=1;i<=n;i++)
		{
			cin>>a[i];
			f[i]=-1;
			e[i].clear();//初始化 
		}
		while(cin>>b>>c && b!=0 || c!=0)
		{
			e[c].push_back(b);
			f[b]=c;
		}
		t=1;
		while(f[t]!=-1) t=f[t];//找根節點 
		dfs(t);
		cout<<max(dp[t][0],dp[t][1])<<endl;
	}
	return 0;
}