首页 > 其他 > 详细

洛谷P1547 Out of Hay 最小生成树 并查集

时间:2017-06-24 00:10:28      阅读:357      评论:0      收藏:0      [点我收藏+]


洛谷P1547 Out of Hay
最小生成树
并查集 路径压缩

 

#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <iomanip>
using namespace std ; 

const int maxn = 2011,maxm = 10011 ; 
struct node{
    int from,to,val ; 
};
node e[maxm] ; 
int n,tot,u,v,m,ans,x,y ;
int fa[maxn] ;  

inline bool cmp(node a,node b) 
{
    return a.val < b.val ; 
}

inline int getfather(int x) 
{
    if(fa[ x ]==x ) return x ; 
    fa[ x ] = getfather( fa[ x ] ) ; 
    return fa[ x ] ; 
}

int main() 
{
    scanf("%d%d",&n,&m) ; 
    for(int i=1;i<=m;i++)  
        scanf("%d%d%d",&e[ i ].from,&e[ i ].to,&e[ i ].val) ; 
    sort(e+1,e+m+1,cmp) ; 
    for(int i=1;i<=n;i++) fa[ i ] = i ; 
    for(int i=1;i<=m;i++) {
        x = e[ i ].from ;   y = e[ i ].to ;
        u = getfather(x) ;  v = getfather(y) ;  
        if(u != v ) 
        {
            fa[ u ] = v ; 
            tot++ ; 
            ans = e[ i ].val ; 
            if(tot==n-1) break ; 
        }
    }
    printf("%d\n",ans) ; 
    return 0 ; 
}

 

洛谷P1547 Out of Hay 最小生成树 并查集

原文:http://www.cnblogs.com/third2333/p/7071986.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!