判断最小生成树是否唯一

在最小生成树的推论中,生成树一定包含连接两个森林中间权值最小的边,所以在做最小生成树的同时统计这些备选边,若备选边大于所需的,则不唯一。

#include<bits/stdc++.h>
#define f(i,l,r) for(i=(l);i<=(r);i++)
using namespace std;
const int MAXN=200005;
struct Node{
	int u,v,w;
	bool operator < (const Node& tmp)const{
		return w<tmp.w;
	}
}a[MAXN];
int n,m,fa[MAXN];
inline void Makeset()
{
	int i;
	f(i,1,n) fa[i]=i;
}
inline int Find(int x)
{
	return fa[x]==x?x:fa[x]=Find(fa[x]);
}
inline bool Union(int x,int y)
{
	x=Find(x);y=Find(y);
	if(x==y) return false;
	fa[x]=y;
	return true;
}
int main()
{
	ios::sync_with_stdio(false);
	int i,j,u,v,w;
	int T;
	cin>>T;
	while(T--){
		long long ans=0,num=0,cnt=0,pos=0;
		cin>>n>>m;
		Makeset();
		f(i,1,m){
			cin>>a[i].u>>a[i].v>>a[i].w;
		}
		sort(a+1,a+1+m);
		f(i,1,m){
			u=a[i].u;v=a[i].v;w=a[i].w;
			if(pos<i){
				pos=i;
				while(pos+1<=m&&a[pos].w==a[pos+1].w) pos++;
				f(j,i,pos){
					if(Find(a[j].u)!=Find(a[j].v)) cnt++;
				}
			}
			if(Union(u,v)){
				num++;
				ans+=w;
				if(num==n-1) break;
			}
		}
		cout<<ans<<endl;
		if(cnt>n-1){
			cout<<"No"<<endl;
		}
		else cout<<"Yes"<<endl;
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值