2017多校联合训练第3场第5题

前40分钟出了两题,后面队友一直在做3题,我一直看5题。原来根本没有遇见过斯坦纳树的题,一看被吓到了。。。

其实这个题就是要把树上除了根节点的其他点分为N个组,相当于给节点标号,要求最小生成树的和的最大值,根本没用到斯坦纳树。

树上每一条边的贡献就是以这条边起点为跟的子树节点不同标号的数量,因为要求最大值,所以子树中标号的种类越多越好,最多为min(k,size[root]);

然后乘一下加起来就好。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,k;
const int maxn = 1000006;
struct node
{
    int to;
    int next;
    long long w;
    node(){}
    node(int a,int b,long long c):to(a),next(b),w(c){}
}edge[maxn*2];
int head[maxn],sz[maxn];
long long cost[maxn];
int tot;
void dfs(int u,int fa)
{
    sz[u] = 1;
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int to = edge[i].to;
        if(to==fa) continue;
        cost[to] = edge[i].w;
        dfs(to,u);
        sz[u] += sz[to];
    }
}
int main()
{
    int u,v;
    long long w;
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        tot = 0;
        memset(head,-1,sizeof(head));
        for(int i=2;i<=n;i++)
        {
            scanf("%d%d%I64d",&u,&v,&w);
            edge[tot] = node(v,head[u],w);
            head[u] = tot++;
            edge[tot] = node(u,head[v],w);
            head[v] = tot++;
        }
        dfs(1,-1);
        long long res = 0;
        for(int i=2;i<=n;i++)
        {
            res += min(sz[i],k)*cost[i];
        }
        printf("%I64d\n",res);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值