HDU 6060 RXD and dividing

2017多校3-5 RXD and dividing

思维题,dfs

题意

给一棵树,1为根。将2~n划分成不同的集合,并将1加入每个集合。使得每个集合构成的最小斯坦纳树的和最大。

思路

把1看成整棵树的根. 问题相当于把 2n 每个点一个[1, k]的标号. 然后根据最小斯坦纳树的定义, (x,fax) 这条边的贡献是 x 子树内不同标号的个数目 difi ​​ . 那么显然有 difimin(k,szi) szi 表示子树大小. 可以通过构造让所有 difi ​ 都取到最大值. 所以答案就是 nx=2w[x][fax]min(szx,k) 。时间复杂度 O(n)

代码

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <iomanip>

using namespace std;

const int MAXN=1100007;
typedef long long LL;

struct Edge
{
    int to;
    LL  co;
    Edge() {}
    Edge(int _a, LL _b) { to=_a, co=_b; }
};

vector<Edge> G[MAXN];
LL res=0;
int dfs(int u,int fa,int k,int cos)
{
    int son=1;
    for(int i=0;i<G[u].size();i++)
    {
        int to=G[u][i].to,cos=G[u][i].co;
        if(to==fa) continue;
        son+=dfs(to, u, k, cos);
    }
    int tmp=min(son, k);
    res+=(LL)tmp*cos;
    return son;
}


int main()
{
    int n, K;
    while(scanf("%d%d", &n, &K)==2)
    {
        for(int i=1;i<=n;i++)
            G[i].clear();

        for(int i=1;i<n;i++)
        {
            int a, b;
            LL  c;
            scanf("%d%d%lld", &a, &b, &c);
            G[a].push_back(Edge(b, c));
            G[b].push_back(Edge(a, c));
        }
        res=0;
        dfs(1, -1, K, 0);
        printf("%lld\n", res);
    }
    //system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值