POJ 2342. Anniversary party 简单树形DP c++ 代码

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxN 6005

int N, L, K;
int dp[maxN + 1][2], father[maxN + 1];
bool visited[maxN];

void treeDp(int index) {
	if (visited[index]) return;
	visited[index] = true;
	for (int i = 1; i <= N; i++) {
		if (father[i] == index) {
			treeDp(i);
			dp[index][0] += max(dp[i][1], dp[i][0]);
			dp[index][1] += dp[i][0];
		}
	}
}

int main(void) {
	memset(dp, 0, sizeof(dp));
	memset(father, -1, sizeof(father)); 
	memset(visited, 0, sizeof(visited));

	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> dp[i][1];
	}

	while (cin >> L >> K && !(L == 0 && K == 0)) 
		father[L] = K;

	// 找根节点
	int root = 1;
	while (father[root] != -1) 
		root = father[root];

	treeDp(root);
	
	cout << max(dp[root][0], dp[root][1]) << endl;
}

你可能感兴趣的:(C++,动态规划,poj,树形DP)