1. 程式人生 > >洛谷P1547 Out of Hay 最小生成樹 並查集

洛谷P1547 Out of Hay 最小生成樹 並查集

ostream int scan stream iomanip blog printf sort ons


洛谷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 最小生成樹 並查集