您的位置:首页 > 其它

contesthunter 6201 走廊泼水节【克鲁斯卡尔+并查集】

2018-07-18 17:26 204 查看

很有意思的题,所以还是截lyddalao的课件

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=6005;
int T,n,f
,s
;
long long ans;
struct qwe
{
int u,v,w;
}a
;
bool cmp(const qwe &a,const qwe &b)
{
return a.w<b.w;
}
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
int zhao(int x)
{
return x==f[x]?x:zhao(f[x]);
}
int main()
{
T=read();
while(T--)
{
n=read();ans=0;
for(int i=1;i<n;i++)
a[i].u=read(),a[i].v=read(),a[i].w=read();
sort(a+1,a+n,cmp);
for(int i=1;i<=n;i++)
f[i]=i,s[i]=1;
for(int i=1;i<n;i++)
{
int fu=zhao(a[i].u),fv=zhao(a[i].v);
ans+=1ll*s[fu]*s[fv]*(a[i].w+1)-a[i].w-1;//cerr<<ans<<endl;
f[fu]=fv;
s[fv]+=s[fu];
}
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: