HDU 3899 JLUCPC (树形DP)

题意:有n个点,每个点有相应的人数,n-1条带权边,从a点的所有人走到b点的花费是a点的人数*边权值,问所有人在哪个点集合能够使花费最小求最小花费。


思路

先dfs求出以1为根节点使每个点后代到这个点集合的花费sum以及这个点及其后代共有几个人cnt

然后枚举每个点i作为集合点(根节点)时他的花费就是sum[i]+他的父节点减去从i来的人的花费+父节点总人数减去从i来的人数*边权

值。并且更新最小花费和sum[i],cnt[i].


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5+5;
const int INF = 0x3f3f3f3f;
int n, v[maxn], cnt[maxn];
ll sum[maxn], ans;
struct node
{
    int v, w;
    node() {}
    node(int vv, int ww): v(vv), w(ww) {}
};
vector<node> g[maxn];

void dfs(int x, int fa)
{
    cnt[x] = v[x]; sum[x] = 0;
    for(int i = 0; i < g[x].size(); i++)
    {
        int to = g[x][i].v;
        int w = g[x][i].w;
        if(to == fa) continue;
        dfs(to, x);
        cnt[x] += cnt[to];
        sum[x] += (sum[to]+(ll)cnt[to]*w);
    }
}

void dfs1(int x, int fa)
{
    for(int i = 0; i < g[x].size(); i++)
    {
        int to = g[x][i].v;
        int w = g[x][i].w;
        if(to == fa) continue;
        sum[to] = sum[to]+(sum[x]-sum[to]-(ll)cnt[to]*w)+(ll)(cnt[x]-cnt[to])*w;
        cnt[to] += (cnt[x]-cnt[to]);
        ans = min(ans, sum[to]);
        dfs1(to, x);
    }
}

int main(void)
{
    while(cin >> n)
    {
        memset(sum, 0, sizeof(sum));
        for(int i = 0; i < maxn; i++)
            g[i].clear();
        for(int i = 1; i <= n; i++)
            scanf("%d", &v[i]);
        for(int i = 1; i < n; i++)
        {
            int u, v, w;
            scanf("%d%d%d", &u, &v, &w);
            g[u].push_back(node(v, w));
            g[v].push_back(node(u, w));
        }
        dfs(1, 0);
        ans = sum[1];
        dfs1(1, 0);
        printf("%lld\n", ans);
    }
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值