树形dp入门 hdu1520 (Anniversary party)

#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;
const int maxn = 6005;
int n, a[maxn];
vector<int>G[maxn];
int x, y;
int dp[maxn][5], into[maxn];
void dfs(int u) {//递归寻找根节点
    for(int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        dfs(v);
        dp[u][0] += max(dp[v][0], dp[v][1]);//父节点不去
        dp[u][1] += dp[v][0];//父节点去
    }
}
int main() {
    while(~scanf("%d", &n)) {
        memset(dp, 0, sizeof(dp));
        memset(into, 0, sizeof(into));
        for(int i = 1; i <= n; i++) G[i].clear();
        for(int i = 1; i <= n; i++) scanf("%d", &dp[i][1]);
        while(~scanf("%d %d", &x, &y), x + y) {
            G[y].push_back(x);
            into[x]++;
        }
        for(int i = 1; i <= n; i++) {
            if(!into[i]) {
                dfs(i);
                printf("%d\n", max(dp[i][0], dp[i][1]));
                break;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/yiqzq/article/details/81108937