Time Limit: 2000/1000 MS
(Java/Others) Memory Limit: 65536/32768 K
(Java/Others)
Total Submission(s): 3861 Accepted
Submission(s): 1800
#include<iostream> #include<string> #define MAX 20000 #define max(x,y) (x>y?x:y) using namespace std; struct node{ int v; node *next; }*head[MAX],tree[MAX]; int ptr, n, t; int dp[MAX][2], w[MAX]; bool visit[MAX]; void initial(){ ptr = 1; memset(head, 0, sizeof(head)); memset(visit, 0, sizeof(visit)); memset(dp, 0, sizeof(dp)); } void addEdge(int x, int y){ tree[ptr].v = y; tree[ptr].next = head[x];head[x] = &tree[ptr++]; tree[ptr].v = x; tree[ptr].next = head[y]; head[y] = &tree[ptr++]; } void tree_DP(int v){ if (visit[v])return; visit[v] = true; node *p = head[v]; while (p){ if (!visit[p->v]){ tree_DP(p->v); dp[v][1] += dp[p->v][0];//如果选当前节点,就不选儿子节点 dp[v][0] += max(dp[p->v][0], dp[p->v][1]); } p = p->next; } dp[v][1] += w[v]; } int main() { int u, v; while (cin >> n){ initial(); for (int i = 1; i <= n; i++){ cin >> w[i]; } while (cin >> u >> v){ if (u + v == 0)break; addEdge(u, v); } tree_DP(1); cout << max(dp[1][0], dp[1][1]) << endl; } return 0; }
原文:http://www.cnblogs.com/littlehoom/p/3561861.html