POJ 2342 Anniversary party(树形DP)

Anniversary party

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
const int maxn = 6000+5;
int n;
int dp[maxn][2], father[maxn];//dp[i][0]表示i不去,dp[i][1]表示i去
bool vis[maxn];//重要,避免重复计算

void tree_dp(int node) {
    vis[node] = true;

    for(int i = 1; i <= n; ++i) {
        if(!vis[i] && father[i] == node) {
            tree_dp(i);//关键点,先顺着往下撸了,搞完孩子再更新自己

            //node来,孩子不来
            dp[node][1] += dp[i][0];
            //node不来,孩子可以来 不来
            dp[node][0] += max(dp[i][0], dp[i][1]);
        }
    }

}

int main() {
    //freopen("data.in", "r", stdin);
    int f, c, root;
    while(scanf("%d", &n) == 1) {
        memset(dp, 0, sizeof(dp));
        memset(father, 0, sizeof(father));
        memset(vis, false, sizeof(vis));

        for(int i = 1; i <= n; ++i)
            scanf("%d", &dp[i][1]);//默认为来

        root = 0;
        while(scanf("%d %d", &c, &f) == 2 ) {
            if(c == 0 && f == 0)
                break;

            father[c] = f;
            root = f;
        }

        while(father[root])//向上找到根节点
            root = father[root];

        //cout << "root=" << root << endl;
        tree_dp(root);
        printf("%d\n", max(dp[root][0], dp[root][1]));
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/ccshijtgc/article/details/81033112