首页 > 其他 > 详细

hdu1520

时间:2015-03-31 20:01:13      阅读:114      评论:0      收藏:0      [点我收藏+]

基本的树形dp

技术分享
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;

const int MAX_N = (int)(6e3) + 5;

int n;
int weight[MAX_N];
vector <int> edge[MAX_N];
bool vis[MAX_N];
int dp[MAX_N][2];
int root;

void dfs(int father, int u)
{
    for (int i = 0; i < (int)edge[u].size(); i++)
    {
        int v = edge[u][i];
        if (v != father)
            dfs(u, v);
    }
    dp[u][0] = 0;
    dp[u][1] = weight[u];
    for (int i = 0; i < (int)edge[u].size(); i++)
    {
        int v = edge[u][i];
        if (v == father)
            continue;
        dp[u][0] += max(dp[v][0], dp[v][1]);
        dp[u][1] += dp[v][0];
    }
}

void input()
{
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &weight[i]);
        edge[i].clear();
    }
    memset(vis, 0, sizeof(vis));
    int a, b;
    while (scanf("%d%d", &a, &b), a | b)
    {
        a--;
        b--;
        vis[a] = true;
        edge[a].push_back(b);
        edge[b].push_back(a);
    }
    for (int i = 0; i < n; i++)
    {
        if (!vis[i])
        {
            root = i;
            break;
        }
    }
}

int main()
{
    while (scanf("%d", &n) != EOF)
    {
        input();
        dfs(-1, root);
        printf("%d\n", max(dp[root][0], dp[root][1]));
    }
    return 0;
}
View Code

 

hdu1520

原文:http://www.cnblogs.com/rainydays/p/4381767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!