HDU1232 暢通工程 並查集

來源:互聯網
上載者:User

標籤:c++   演算法   並查集   hdu   最佳化   

這道題跟HDU 1213 How Many Tables 並查集非常接近,都是赤裸裸的並查集的題。

思路:假設還需要建n-1條路,每並一次就自減1。

參考代碼:

#include<stdio.h>int fa[1000];int find(int u){    return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){    int i,n,m,u,v,x,y;    scanf("%d%d",&n,&m);    while (n)    {        for (i=1;i<=n;i++) fa[i]=i;        for (i=1;i<=m;i++)        {            scanf("%d%d",&u,&v);            x=find(u);y=find(v);            if (x!=y)            {                fa[x]=y;                n--;            }        }        n--;        printf("%d\n",n);       scanf("%d%d",&n,&m);    }   return 0;}

最佳化:先用數組儲存m組數,然後只對這些節點的根節點

賦初值fa[u[i]]=u[i];fa[v[i]]=v[i];

參考代碼:

#include<stdio.h>int fa[1000],u[1000],v[1000];int find(int u){    return fa[u]==u?u:fa[u]=find(fa[u]);}int main(){    int i,n,m,x,y;    scanf("%d%d",&n,&m);    while (n)    {        for (i=1;i<=m;i++)        {            scanf("%d%d",&u[i],&v[i]);            fa[u[i]]=u[i];            fa[v[i]]=v[i];        }        for (i=1;i<=m;i++)        {          x=find(u[i]);y=find(v[i]);            if (x!=y)            {                fa[x]=y;                n--;            }        }        n--;        printf("%d\n",n);       scanf("%d%d",&n,&m);    }   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.