第二道树形DP,先是MLE。后来仅需改小邻接矩阵的第二个维度到30就过了。
#include <cstdio>
#include <cstring>
#include <cstdlib> #define MAXN 6005 int rat[MAXN];
int dp[MAXN][];
int adj[MAXN][];
bool visit[MAXN];
int n; int max(int a, int b) {
return a>b ? a:b;
} void dfs(int r) {
int i, v; visit[r] = true;
dp[r][] = rat[r];
for (i=; i<=adj[r][]; ++i) {
v = adj[r][i];
if (visit[v])
continue;
dfs(v);
// r node not attend, v get the maximum
dp[r][] += max(dp[v][], dp[v][]);
// r node attend, v not attend.
dp[r][] += dp[v][];
}
} int main() {
int i, j, k;
int a, b; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
#endif while (scanf("%d", &n) != EOF) {
for (i=; i<=n; ++i)
scanf("%d", &rat[i]); memset(adj, , sizeof(adj));
memset(visit, false, sizeof(visit));
memset(dp, , sizeof(dp));
while (scanf("%d %d", &a, &b)!=EOF && (a||b)) {
++adj[a][];
adj[a][adj[a][]] = b;
++adj[b][];
adj[b][adj[b][]] = a;
} dfs();
printf("%d\n", max(dp[][], dp[][]));
} return ;
}