最小生成树kruskal

#include<iostream>
#include<cstdio>
using namespace std;
struct node{
	int x,y,w;
}a[10001],t;
int f[10001],rank[10001];
void qsort(int l,int r){  
    int mid=a[(l+r)/2].w,i,j;  
    i=l;j=r;  
    while(i<j){  
        while(i<=j && a[i].w<mid)i++;  
        while(i<=j && a[j].w>mid)j--;  
        if(i<=j){  
            t=a[i];a[i]=a[j];a[j]=t;  
            i++;j--;  
        }  
    }  
    if(l<j)qsort(l,j);  
    if(i<r)qsort(i,r);  
}  
int father(int x){
    if(f[x]!=x)  
        f[x]=father(f[x]);  
    return f[x];
}
void link(int x,int y){
    if(rank[father(x)]<=rank[father(y)]){
	    f[father(x)]=father(y); 
	    rank[father(y)]++;
	}else{
	    f[father(y)]=father(x); 
	    rank[father(x)]++;
	}
}
int find(int x,int y){
    if(father(x)==father(y))return 0;
    return 1;
}
int main(){
	int i,j,k,m,n;
	cin>>n>>m;
	for(i=1;i<=m;i++)
	    cin>>a[i].x>>a[i].y>>a[i].w;
	qsort(1,m);
	int p=n,sum=0;
	for(i=1;i<=n;i++)f[i]=i;
	for(i=1;i<m && p!=1;i++){
	    if(find(a[i].x,a[i].y)==1){
		    p--;
		    link(a[i].x,a[i].y); 
		    sum+=a[i].w;
		}
	}
	cout<<sum<<endl;
	return 0;
}

你可能感兴趣的:(算法,最小生成树,C语言,图论,kruskal)