只有1个对其他都ac 大佬救救
查看原帖
只有1个对其他都ac 大佬救救
1174031
tutu_niu楼主2024/1/23 15:57
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<string>
using namespace std;
#define N 1010
#define M 100010
int a[N];
struct  Road1{
 int x;
 int y;
 int t;
} road[M];
int  find(int k){return a[k]=k?k:a[k]=find(a[k]);}
bool Union(int x,int y)
{
    int c = find(x);
    int v = find(y);
    if (c != v) 
    {
        a[c] = v;
        return true;
    }
    return false;
}
bool cmp( Road1 r1,Road1 r2)
{   return r1.t<=r2.t ;}
int main(){
int n,m,cnt,tm;
 memset(road,0,sizeof road);
cin>>n>>m;
cnt=n;
for(int i=1;i<=n;i++){a[i]=i;}
for(int i=1;i<=m;i++){ cin>>road[i].x>>road[i].y>>road[i].t; }
sort(road+1,road+1+m,cmp);
for(int i=1;i<=m;i++){
   
   if(Union(road[i].x,road[i].y)){cnt--;}
   if(cnt==1){                  ///两个if语句顺序不能颠倒
    tm=road[i].t;
     break;
   } 
}
if(cnt>1){cout<<-1<<"\n";}
else{cout<<tm<<"\n";}
    return 0;
}
2024/1/23 15:57
加载中...