#include<iostream>
using namespace std;
long e,tot=0;
long checkset[20000];
long a[20000][3];
long find_root(int i){
if(checkset[i]==i){
return i;
}
else find_root(checkset[i]);
}
void qsort(int l,int r){
int i,j;
long t;
i=l; j=r; t=a[i][2];
do{
while(a[j][2]>t) j--;
while(a[i][2]<t) i++;
if(i<=j){
e=a[j][2];
a[j][2]=a[i][2];
a[i][2]=e;
e=a[j][0];
a[j][0]=a[i][0];
a[i][0]=e;
e=a[j][1];
a[j][1]=a[i][1];
a[i][1]=e;
i++;
j--;
}
}while(i<=j);
if(l<j) qsort(l,j);
if(i<r) qsort(i,r);
}
int main(){
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++){
checkset[i]=i;
cin>>a[i][0]>>a[i][1]>>a[i][2];
}
//输入结束
qsort(0,m-1);
for(int i=0;i<n-1;i++)
if(checkset[a[i][0]]!=checkset[a[i][1]]){
tot+=a[i][2];
if(checkset[a[i][0]]<checkset[a[i][1]]) checkset[checkset[a[i][1]]]=checkset[a[i][0]];
else checkset[checkset[a[i][0]]]=checkset[a[i][1]];
}
cout<<tot;
return 1;
}
kruscal
最新推荐文章于 2025-07-28 10:16:16 发布