洛谷P1111 修复公路

并查集的模板题,唯一需要注意的是记录一下元素个数,看看最终是否全部联通

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
template<class T>void read(T &x)
{
	int f=0;x=0;char ch=getchar();
	while(ch<'0'||ch>'9')  {f|=(ch=='-');ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
	x=f?-x:x;
}
struct yhh{
	int x,y,t;
	bool operator<(const yhh &x)const{return t<x.t;}
}a[100007];
int fa[100007],tot[10007],n,m,ans,res;
int find(int x)
{
	while(x!=fa[x]) x=fa[x];
	return x;
}
void qwq(int x,int y)
{
	x=find(x),y=find(y);
	fa[x]=y,tot[y]+=tot[x];
	res=max(res,tot[y]);
}
int main()
{
	read(n),read(m);
	for(int i=1;i<=m;++i)
	  read(a[i].x),read(a[i].y),read(a[i].t);
	sort(a+1,a+m+1);
	for(int i=1;i<=n;++i)
	  fa[i]=i,tot[i]=1;
	 for(int i=1;i<=m;++i)
	 {
	 	if(find(a[i].x)==find(a[i].y)) continue;
	 	qwq(a[i].x,a[i].y);
	 	ans=max(ans,a[i].t);
	}	
	if(res!=n) printf("-1");
	else       printf("%d",ans);
	return 0;
}

  

转载于:https://www.cnblogs.com/Peper/p/9563125.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值