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

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

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

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

然后乘一下加起来就好。

#include
#include
#include
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;
}


你可能感兴趣的:(树)