51nod 1212 無向圖最小產生樹 (Kruskal)

來源:互聯網
上載者:User


N個點M條邊的無向連通圖,每條邊有一個權值,求該圖的最小產生樹。 Input

第1行:2個數N,M中間用空格分隔,N為點的數量,M為邊的數量。(2 <= N <= 1000, 1 <= M <= 50000)第2 - M + 1行:每行3個數S E W,分別表示M條邊的2個頂點及權值。(1 <= S, E <= N,1 <= W <= 10000)
Output
輸出最小產生樹的所有邊的權值之和。
Input樣本
9 141 2 42 3 83 4 74 5 95 6 106 7 27 8 18 9 72 8 113 9 27 9 63 6 44 6 141 8 8
Output樣本
37

#include<iostream>#include<algorithm>#include<cstdio>using namespace std;int fa[1111];void init(int n){for(int i=0;i<=n;i++) fa[i]=i;}int find(int x){int r;r=x;while(fa[r]!=r) r=fa[r];int i=x,j;while(i!=r) {j=fa[i];fa[i]=r;i=j;}return r;}struct node{int u;int v;int num;}a[55555];bool cmp(node x,node y){if(x.num<y.num) return true;return false;}int main(){ ios::sync_with_stdio(false);  int i,j,n,m,ans;ans=0;cin>>n>>m;init(n);for(i=0;i<m;i++) {cin>>a[i].u>>a[i].v>>a[i].num;}sort(a,a+m,cmp);for(i=0;i<m;i++) {int fx=find(a[i].u);int fy=find(a[i].v);if(fx!=fy) {fa[fx]=fy;ans+=a[i].num;}}cout<<ans<<endl;return 0;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.