题目链接:http://poj.org/problem?id=2342
题意:n个人每个人有一个conviviality ratings,而且任何人之间是从属的关系。有一个活动,组织者希望来参加的人互相之间没有直接的从属关系,问最大conviviality ratings总和。
以1节点开始dfs,每次遍历时根据当前点来或者不来做决策,如果当前节点来,则它的儿子不来,否则两个都要遍历,取最大值。用dp(i,j)数组存状态,i表示编号j表示来(1)或者不来(0),dp(i,0)+=max(dfs(i's son, 0), dfs(i's son, 1)) dp(i,1)+=dfs(i's son, 0)
1 /* 2 ━━━━━┒ギリギリ♂ eye! 3 ┓┏┓┏┓┃キリキリ♂ mind! 4 ┛┗┛┗┛┃\○/ 5 ┓┏┓┏┓┃ / 6 ┛┗┛┗┛┃ノ) 7 ┓┏┓┏┓┃ 8 ┛┗┛┗┛┃ 9 ┓┏┓┏┓┃ 10 ┛┗┛┗┛┃ 11 ┓┏┓┏┓┃ 12 ┛┗┛┗┛┃ 13 ┓┏┓┏┓┃ 14 ┃┃┃┃┃┃ 15 ┻┻┻┻┻┻ 16 */ 17 #include <algorithm> 18 #include <iostream> 19 #include <iomanip> 20 #include <cstring> 21 #include <climits> 22 #include <complex> 23 #include <fstream> 24 #include <cassert> 25 #include <cstdio> 26 #include <bitset> 27 #include <vector> 28 #include <deque> 29 #include <queue> 30 #include <stack> 31 #include <ctime> 32 #include <set> 33 #include <map> 34 #include <cmath> 35 using namespace std; 36 #define fr first 37 #define sc second 38 #define cl clear 39 #define BUG puts("here!!!") 40 #define W(a) while(a--) 41 #define pb(a) push_back(a) 42 #define Rint(a) scanf("%d", &a) 43 #define Rs(a) scanf("%s", a) 44 #define Cin(a) cin >> a 45 #define FRead() freopen("in", "r", stdin) 46 #define FWrite() freopen("out", "w", stdout) 47 #define Rep(i, len) for(int i = 0; i < (len); i++) 48 #define For(i, a, len) for(int i = (a); i < (len); i++) 49 #define Cls(a) memset((a), 0, sizeof(a)) 50 #define Clr(a, x) memset((a), (x), sizeof(a)) 51 #define Full(a) memset((a), 0x7f7f7f, sizeof(a)) 52 #define lrt rt << 1 53 #define rrt rt << 1 | 1 54 #define pi 3.14159265359 55 #define RT return 56 #define lowbit(x) x & (-x) 57 #define onecnt(x) __builtin_popcount(x) 58 typedef long long LL; 59 typedef long double LD; 60 typedef unsigned long long ULL; 61 typedef pair<int, int> pii; 62 typedef pair<string, int> psi; 63 typedef pair<LL, LL> pll; 64 typedef map<string, int> msi; 65 typedef vector<int> vi; 66 typedef vector<LL> vl; 67 typedef vector<vl> vvl; 68 typedef vector<bool> vb; 69 70 const int maxn = 6060; 71 vector<int> G[maxn]; 72 int dp[maxn][2]; 73 int w[maxn]; 74 int n; 75 76 int dfs(int p, int u, int s) { 77 if(dp[u][s] != -1) return dp[u][s]; 78 int v; 79 if(s) { 80 dp[u][s] = w[u]; 81 Rep(i, G[u].size()) { 82 v = G[u][i]; 83 if(v == p) continue; 84 dp[u][s] += dfs(u, v, 0); 85 } 86 } 87 else { 88 dp[u][s] = 0; 89 Rep(i, G[u].size()) { 90 v = G[u][i]; 91 if(v == p) continue; 92 dp[u][s] += max(dfs(u, v, 0), dfs(u, v, 1)); 93 } 94 } 95 return dp[u][s]; 96 } 97 98 int main() { 99 // FRead(); 100 int u, v; 101 while(~Rint(n)) { 102 Rep(i, n+5) G[i].clear(); 103 Clr(dp, -1); 104 For(i, 1, n+1) Rint(w[i]); 105 while(~Rint(u) && ~Rint(v) && u + v) { 106 G[u].pb(v); G[v].pb(u); 107 } 108 int ret = max(dfs(0, 1, 0), dfs(0, 1, 1)); 109 printf("%d ", ret); 110 } 111 RT 0; 112 }