TYVJ 1391 走廊潑水節【生成樹】
阿新 • • 發佈:2018-12-13
大意
給定一棵
個節點的樹,要求增加若干條邊,把這棵樹擴充為完全圖,並完全圖的唯一最小生成樹仍然是這棵樹。求增加的邊的權值總和最小是多少。
資料範圍:
,原有的邊權均為非負整數
思路
首先題目要求完全圖的唯一最小生成樹仍然是這棵樹
,所以對於對兩個點集合
,
之間的連邊必須大於原長度,而又要求最小,所以自然是權值+1
那麼我們對於一條邊
,設
表示
所在的點集,
表示
所在的點集,而
與
之間必定會新增
條邊,而每條邊的長度都為
,如圖
作圖網頁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);
}
}