Networking POJ1287 最小生成樹 Kruscal (根據Kruscal特點,不用判斷重邊)
阿新 • • 發佈:2018-11-19
http://poj.org/problem?id=1287
給定點以及邊,這裡需要注意的是50個點最多,那麼邊最多有50*49條,注意陣列不要太小了。
Kruscal模板題
#include<iostream> #include<math.h> #include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; struct node { int u; int v; int w; } edge[2600]; int pre[100]; int n,m; bool cmp(const node&a,const node&b ) { return a.w<b.w;//定義排序方法; } int find(int x) { return x==pre[x]?x:pre[x]=find(pre[x]); //return } void unions(int x,int y) { int fx=find(x); int fy=find(y); if(fx!=fy) { pre[fx]=fy; } }//並查集方法; void createGraph() { for(int i=1; i<=n; i++)pre[i]=i; for(int i=1; i<=m; i++) { cin>>edge[i].u>>edge[i].v>>edge[i].w; } } int kruscal() { int ans=0; sort(edge+1,edge+m+1,cmp);//排序; for(int i=1; i<=m; i++) { if(find(edge[i].u)!=find(edge[i].v)) {//如果沒有公共節點就合併; unions(edge[i].u,edge[i].v); ans+=edge[i].w; } } return ans; } int main() { while(cin>>n>>m&&n) { createGraph(); cout<<kruscal()<<endl; } }