POJ 2342 Anniversary party(树形DP)

#pragma warning(disable:4996)
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
#define N 6005
using namespace std;

//树形dp:通过“所有”子节点的信息来更新父节点的信息

//g[u]里面放着u的所有儿子
vector<int>g[N];
//dp[i][0]表示第i个人不参加聚会得到的最大值,dp[i][1]表示第i个人参加聚会能得到的最大值
//转移方程是:dp[i][0]+=max(dp[son][1],dp[son][0]) 初始化时dp[i][0]为0
//           dp[i][1]+=dp[son][0]  初始化dp[i][1]为a[i]

//借助vis数组来找到root
int vis[N], dp[N][2], a[N];

void dfs(int u){
	dp[u][1] = a[u];
	dp[u][0] = 0;
	for (int i = 0; i < g[u].size(); i++){
		int v = g[u][i];
		dfs(v);
		dp[u][0] += max(dp[v][1], dp[v][0]);
		dp[u][1] += dp[v][0];
	}
}

int main(){
	int n;
	while (scanf("%d", &n) != EOF){
		if (n == 0){
			scanf("%d", &n);
			break;
		}
		memset(dp, 0, sizeof dp);
		for (int i = 0; i <= n; i++){
			g[i].clear();
			vis[i] = false;
		}

		for (int i = 1; i <= n; i++)scanf("%d", a + i);

		for (int i = 1; i < n; i++){
			int u, v; scanf("%d %d", &u, &v);
			g[v].push_back(u);
			vis[u] = true;
		}

		int root = 0;
		for (int i = 1; i <= n; i++){
			if (vis[i] == false){
				root = i;
				break;
			}
		}

		dfs(root);

		printf("%d\n", max(dp[root][0], dp[root][1]));

	}
	return 0;
}

你可能感兴趣的:(POJ 2342 Anniversary party(树形DP))