并查集的模板题,唯一需要注意的是记录一下元素个数,看看最终是否全部联通
#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;
}