poj 2395 Kruskal

本文介绍了一种使用Kruskal算法寻找加权图的最小生成树的方法。通过不断选择权重最小且不会形成环的边来构建最小生成树。文章详细展示了如何初始化并查集确定顶点所属集合,并通过比较边的权重进行排序,最终实现最小生成树的构建。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include<vector>
#include<string>
using namespace std;
int N,M;
struct graph{
  int u,v;
  int w;
}p[10010];
bool cmp(graph m,graph n){
   return m.w<n.w;
}
int father[2020];
int Find(int x){
   if(father[x]==x)
     return x;
    return father[x]=Find(father[x]);
}
bool Union(int x,int y){
   x=Find(x);
   y=Find(y);
   if(x==y)
     return true;//祖先相同,是同一个集合;
   if(x>y)
       father[x]=y;
    if(x<y)
       father[y]=x;
    return false;

}
int main(){
    while(cin>>N>>M){
        for(int i=0;i<M;i++){
           scanf("%d%d%d",&p[i].u,&p[i].v,&p[i].w);
        }
        for(int i=0;i<N;i++)
           father[i]=i;
        sort(p,p+M,cmp);
        int count=0;
        int k;
        for(int i=0;i<M;i++){
           if(!Union(p[i].u,p[i].v))
           {
               count++;
               k=i;
           }
           if(count==N-1)
              break;

        }
        cout<<p[k].w<<endl;




    }




}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值