A - 这题可以做 HDU - 1520 树形DP

题意:在一个有根树上每个节点有一个权值,每相邻的父亲和孩子只能选择一个,问怎么选择总权值之和最大。

#include<cstdio>
#include<vector>
#include<stack>
#include<set>
#include<algorithm>
using namespace std;
const int maxn = 6100;
vector<int>v[maxn];
int n,happy[maxn],dp[maxn][2];
void dfs(int from, int pre) {
    dp[from][1] = happy[from];
    for (int i = 0;i < v[from].size();i++) {
        int to = v[from][i];
        if (to == pre)continue;
        dfs(to, from);
        dp[from][1] += dp[to][0];
        dp[from][0] += max(dp[to][1], dp[to][0]);
    }
    
}
int main() {
    while (~scanf("%d", &n))
    {
        for (int i = 1;i <= n;i++)v[i].clear();
        memset(dp, 0, sizeof dp);
        for (int i = 1;i <= n;i++)scanf("%d", happy + i);
        int from, to;
        while(scanf("%d%d", &from, &to),from+to)
        {
            v[from].push_back(to);
            v[to].push_back(from);
        }
        dfs(1, 0);
        printf("%d\n", max(dp[1][0], dp[1][1]));
    }
    
}

 

posted @ 2020-02-07 21:38  programmer_w  阅读(0)  评论(0)    收藏  举报