依旧并查集
2025-08-06 09:55:53
发布于:上海
4阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
const int N=1e3+5;
const int M=1e5+5;
const int INF=2e9;
long long n,m,f[N],ans=0;
struct node{
int st,end,time;
}a[M];
bool cmp(node x,node y){
return x.time<y.time;
}
int find(int x){
if(f[x]==x)return x;
return f[x]=find(f[x]);
}
void merge(int x,int y){
x=find(x);
y=find(y);
f[x]=y;
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
f[i]=i;
}
for(int i=1;i<=m;i++){
cin>>a[i].st>>a[i].end>>a[i].time;
}
sort(a+1,a+m+1,cmp);
int cnt=0;
for(int i=1;i<=m;i++){
if(find(a[i].st)!=find(a[i].end)){
merge(a[i].st,a[i].end);
cnt++;
}
if(cnt==n-1){
cout<<a[i].time;
return 0;
}
}
cout<<-1;
return 0;
}
这里空空如也
有帮助,赞一个