1. 程式人生 > >TYVJ 1391 走廊潑水節【生成樹】

TYVJ 1391 走廊潑水節【生成樹】

連結太長放不下


大意

給定一棵 N N 個節點的樹,要求增加若干條邊,把這棵樹擴充為完全圖,並完全圖的唯一最小生成樹仍然是這棵樹。求增加的邊的權值總和最小是多少。
資料範圍: N 6000

N\leq6000 ,原有的邊權均為非負整數


思路

首先題目要求完全圖的唯一最小生成樹仍然是這棵樹,所以對於對兩個點集合 x x y y

之間的連邊必須大於原長度,而又要求最小,所以自然是權值+1

那麼我們對於一條邊 ( x , y , w ) (x,y,w)

,設 S x S_x 表示 x x 所在的點集, S y S_y 表示 y y 所在的點集,而 S x S_x S y S_y 之間必定會新增 S x + S y 1 |S_x|+|S_y|-1 條邊,而每條邊的長度都為 w + 1 w+1 ,如圖
interesting
作圖網頁ProcessOn


程式碼

#include<cctype>
#include<cstdio>
#include<algorithm>
using namespace std;int n,f[6010],s[6010],T;
long long ans;
inline char Getchar()
{
    static char buf[100000],*p1=buf+100000,*pend=buf+100000;
    if(p1==pend)
	{
        p1=buf; pend=buf+fread(buf,1,100000,stdin);
        if (pend==p1) return -1;
    }
    return *p1++;
}
inline int read()
{
	char c;int d=1,f=0;
	while(c=Getchar(),!isdigit(c))if(c==45)d=-1;f=(f<<3)+(f<<1)+c-48;
	while(c=Getchar(),isdigit(c)) f=(f<<3)+(f<<1)+c-48;
	return d*f;
}
inline void write(register long long x)
{
	if(x<0)write(45),x=-x;
	if(x>9)write(x/10);
	putchar(x%10+48);
	return;
}//以上為輸入輸出優化
struct node{int x,y,w;}edge[6010];
inline bool cmp(node x,node y){return x.w<y.w;}//排序
inline int find(register int x){return x==f[x]?x:f[x]=find(f[x]);}//判斷所處集合
signed main()
{
	T=read();
	while(T--)
	{
		n=read();
		for(register int i=1;i<n;i++)edge[i]=(node){read(),read(),read()};
		sort(edge+1,edge+n,cmp);
		for(register int i=1;i<=n;i++) f[i]=i,s[i]=1;
		ans=0;
		for(register int i=1;i<n;i++)
		{
			int fx=find(edge[i].x),fy=find(edge[i].y);
			if(fx==fy) continue;
			ans+=(long long)(edge[i].w+1)*(s[fx]*s[fy]-1);
			f[fx]=fy;s[fy]+=s[fx];//集合被合併
		}
		write(ans);putchar(10);
	}
}