• [Tvvj1391]走廊泼水节(最小生成树)


    [Tvvj1391]走廊泼水节

    Description

    给定一棵N个节点的树,要求增加若干条边,把这棵树扩充为完全图,并满足图的唯一最小生成树仍然是这棵树。求增加的边的权值总和最小是多少。
    完全图:完全图是一个简单的无向图,其中每对不同的顶点之间都恰连有一条边相连(来自百度百科)

    输入格式

    本题为多组数据
    第一行t,表示有t组测试数据
    对于每组数据
    第一行N,表示水龙头的个数(当然也是OIER的个数);
    2到N行,每行三个整数X,Y,Z;表示水龙头X和水龙头Y有一条长度为Z的小道

    输出格式

    对于每组数据,输出一个整数,表示修建的所有道路总长度的最短值。

    样例输入

    2
    3
    1 2 2
    1 3 3
    4
    1 2 3
    2 3 4
    3 4 5

    样例输出

    4
    17

    数据范围与约定

    • 每个测试点最多10组测试数据
      50% n<=1500;
      100% n<=6000
      100% z<=100

    样例解释

    第一组数据,在2和3之间修建一条长度为4的道路,是这棵树变成一个完全图,且原来的树依然是这个图的唯一最小生成树.

    模拟最小生成树的过程,将初始边排序,对于初始边的两个端点(x,y),为了保证将这两个集合连接起来的边是((x,y)),那么两个集合其他之间的边权(>=v(x,y)),所以对于两个集合的添加边,最小的边权为(v(x,y)+1),所以统计一下两个集合内有多少个点,算出两个集合的添加边为多少即可。

    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int read()
    {
    	int x=0,w=1;char ch=getchar();
    	while(ch>'9'||ch<'0') {if(ch=='-')w=-1;ch=getchar();}
    	while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    	return x*w;
    }
    const int N=6010;
    int n,cnt,ans;
    int head[N],fa[N],size[N];
    struct node{
    	int x,y,z;
    }f[N];
    bool cmp(node p,node q){return p.z<q.z;}
    void clear()
    {
    	ans=0;cnt=0;memset(head,0,sizeof(head));for(int i=1;i<=n;i++) fa[i]=i,size[i]=1;
    }
    int gfa(int x){if(x==fa[x])return x;return fa[x]=gfa(fa[x]);}
    int main()
    {
    	int t=read();
    	while(t--)
    	{
    		n=read();clear();
    		for(int i=1;i<n;i++)
    		{
    			f[i].x=read();f[i].y=read();f[i].z=read();
    		}
    		sort(f+1,f+n,cmp);
    		for(int i=1;i<n;i++)
    		{
    			int xx=gfa(f[i].x),yy=gfa(f[i].y);
    			if(xx==yy) continue;
    			ans+=(f[i].z+1)*(size[xx]*size[yy]-1);
    			fa[xx]=yy;size[yy]+=size[xx];
    		}
    		cout<<ans<<endl;
    	}
    }
    
  • 相关阅读:
    PAT (Advanced Level) 1086. Tree Traversals Again (25)
    PAT (Advanced Level) 1085. Perfect Sequence (25)
    PAT (Advanced Level) 1084. Broken Keyboard (20)
    PAT (Advanced Level) 1083. List Grades (25)
    PAT (Advanced Level) 1082. Read Number in Chinese (25)
    HDU 4513 吉哥系列故事――完美队形II
    POJ Oulipo KMP 模板题
    POJ 3376 Finding Palindromes
    扩展KMP
    HDU 2289 Cup
  • 原文地址:https://www.cnblogs.com/lsgjcya/p/9329245.html
Copyright © 2020-2023  润新知