基本的树形dp
#include <cstring> #include <cstdio> #include <vector> using namespace std; const int MAX_N = (int)(6e3) + 5; int n; int weight[MAX_N]; vector <int> edge[MAX_N]; bool vis[MAX_N]; int dp[MAX_N][2]; int root; void dfs(int father, int u) { for (int i = 0; i < (int)edge[u].size(); i++) { int v = edge[u][i]; if (v != father) dfs(u, v); } dp[u][0] = 0; dp[u][1] = weight[u]; for (int i = 0; i < (int)edge[u].size(); i++) { int v = edge[u][i]; if (v == father) continue; dp[u][0] += max(dp[v][0], dp[v][1]); dp[u][1] += dp[v][0]; } } void input() { for (int i = 0; i < n; i++) { scanf("%d", &weight[i]); edge[i].clear(); } memset(vis, 0, sizeof(vis)); int a, b; while (scanf("%d%d", &a, &b), a | b) { a--; b--; vis[a] = true; edge[a].push_back(b); edge[b].push_back(a); } for (int i = 0; i < n; i++) { if (!vis[i]) { root = i; break; } } } int main() { while (scanf("%d", &n) != EOF) { input(); dfs(-1, root); printf("%d\n", max(dp[root][0], dp[root][1])); } return 0; }
原文:http://www.cnblogs.com/rainydays/p/4381767.html