POJ 1861 Network(MST)

來源:互聯網
上載者:User

題目連結:http://poj.org/problem?id=1861

表示這個題目不想寫的,因為一看就是個最小產生樹問題,肯定能寫出來,後來想想這個英文題目看懂也不容易,就寫了吧

以前寫最小產生樹都是用prim寫的,今天要還用prim就真沒意思了,換下克魯斯卡爾吧,正好複習下並查集,但是鬼知道

題目給的範例竟然是錯的,鬱悶了一會後反正是Virtual judge,提交一下試試,過了!

#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>using namespace std;#define maxn 20000int rec[maxn];struct point{    int a;    int b;    int len;}po[maxn];int ans[maxn],pos,my_max;int n,m;int cmp(const void *a,const void *b){    return (*(point*)a).len < (*(point*)b).len ? -1 : 1;}int init(){    for(int i=0;i<=n;i++)    rec[i]=i;    return 0;}int find_root(int a){    int i=a,j;    while(rec[a]!=a)    {        a=rec[a];    }    while(i!=a)    {        j=rec[i];        rec[i]=a;        i=j;    }    return a;}int union_set(int a,int b){    a=find_root(a);    b=find_root(b);    if(a<b)    rec[b]=a;    else    rec[a]=b;    return 0;}int ku(){    init();    int i,j,k;    my_max=0;    for(i=0;i<m;i++)    {        if(find_root(po[i].a)!=find_root(po[i].b))            ans[pos++]=i,union_set(po[i].a,po[i].b),my_max=po[i].len;    }    return 0;}int main(){    int i,j,k;    while(scanf("%d%d",&n,&m)!=EOF)    {        for(i=0;i<m;i++)        scanf("%d%d%d",&po[i].a,&po[i].b,&po[i].len);        qsort(po,m,sizeof(po[0]),cmp);        pos=0;        ku();        printf("%d\n%d\n",my_max,pos);        for(i=0;i<pos;i++)            printf("%d %d\n",po[ans[i]].a,po[ans[i]].b);    }    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.