JZOJ 2940. 【NOIP2012模拟8.10】生成输入数据


题目:

传送门


分析:

我们将每条边的两个端点看成是两个集合: s 1 、 s 2 s_1、s_2 s1s2
而因为我们每次都通过一条在最小生成树上的边将两个集合连起来,所以两个集合相连的其他边都是大于在最小生成树上的边的
而因为是完全图,所以两个集合每个点相连,一共有 ∣ s 1 ∣ ∗ ∣ s 2 ∣ |s_1|*|s_2| s1s2种方案,但因为有一条是在最小生成树上的边,所以要 − 1 - 1 1
故答案每次累加时,应为 a n s + = ∣ s 1 ∣ ∗ ∣ s 2 ∣ − 1 ans+=|s_1|*|s_2|-1 ans+=s1s21


代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<list>
#include<ctime>
#include<iomanip>
#include<string>
#include<bitset>
#include<deque>
#include<set>
#define LL long long
using namespace std;
inline LL read(){
	LL d=0,f=1;char s=getchar();
	while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
	while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
	return d*f;
}
struct node{
	LL a,b,c;
}e[20005];
LL f[20005],cnt[20005];
LL find(LL x) {return f[x]==x?x:f[x]=find(f[x]);}
bool cmp(node x,node y) {return x.c<y.c;}
int main()
{
	LL q=read();
	while(q--)
	{
		LL n=read();
		for(LL i=1;i<=n;i++) f[i]=i,cnt[i]=1;
		LL ans=0;
		for(LL i=1;i<n;i++) e[i].a=read(),e[i].b=read(),e[i].c=read();
		sort(e+1,e+n,cmp);
		for(LL i=1;i<n;i++)
		{
			if(find(e[i].b)==find(e[i].a)) continue;
			ans+=e[i].c;
			ans+=(e[i].c+1)*(cnt[find(e[i].b)]*cnt[find(e[i].a)]-1);
			cnt[find(e[i].b)]+=cnt[find(e[i].a)];
			f[find(e[i].a)]=find(e[i].b);
		}
		printf("%lld\n",ans);
	}
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值