MST......

Kruskal

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
struct jc{
    int fm,to,dist;
}e[3000];
int f[3000],g[1001][1001],n,ans=0,m,maxint=1073741824;  
int find(int x) {
	if (f[x]!=x) f[x]=find(f[x]);  
    return f[x];  
}
//路径压缩 
void merge(int x,int y){
    int xx=find(x);
	int yy=find(y);
    f[xx]=yy;
}

bool cmp(jc a,jc b){
	 return a.dist<b.dist; 
}
//cmp
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	    scanf("%d%d%d",&e[i].fm,&e[i].to,&e[i].dist);
	sort(e+1,e+m+1,cmp);
 	for(int i=1;i<=n;i++) f[i]=i;
 	int rst=n;//用于记录加入的边 
  	for(int i=1;i<=m && rst>1;i++)
    {
        int x=e[i].fm,y=e[i].to;
        if(find(x)!=find(y))//查
        {
            merge(x,y);//并 
            rst--;
            ans+=e[i].dist;
        }
    }
    printf("%d",ans);
	return 0;
}



posted @ 2015-11-03 11:34  Mr.doublerun  阅读(13)  评论(0)    收藏  举报