【圖論05】並查集 1004 A Bug’s Life

來源:互聯網
上載者:User

  

這題除了用並查集之外,還可以DFS、BFS、二分圖過!

並查集:題意:
首先給定n只蟲子,然後給出m個情況。每個情況給出兩隻蟲子交配,當出現兩隻蟲子為同性戀時,便判錯。

解題思路:
首先肯定是並查集,將同一類的蟲子併到同一個集合。
我剛開始的時候想把所以有關係的蟲子併到一個集合,然後通過其到根節點的步數來判斷。結果wa了。。
後來學長指點,將蟲子分為兩個集合,一個為共,一個為母。
如果兩字蟲子的父節點為同一個,則為同性戀。
如果兩隻蟲子都沒有標記過,則將兩隻蟲子分別歸為到不同的性別。代碼:

#include<iostream>#include<cstdio>#include<cstring>using namespace std;int f[2005],sex[2005],r[2005];int find(int x){    if (x!=f[x])        f[x]=find(f[x]);    return f[x];}void uni(int x,int y){    x=find(x);    y=find(y);    if (x==y) return;    else if (r[x]>r[y])        f[y]=x;    else if (r[x]==r[y])    {        r[x]++;        f[y]=x;    }    else        f[x]=y;}int main (){    int t,n,m,i,a,b,p=1;    cin>>t;    while(t--)    {        bool ass=true;        scanf("%d%d",&n,&m);        memset(f,0,sizeof(f));        memset(sex,0,sizeof(sex));        memset(r,0,sizeof(r));        for (i=1; i<=n; i++)            f[i]=i;        for (i=1; i<=m; i++)        {            scanf("%d%d",&a,&b);            if (ass)            {                if (find(a)==find(b))                    ass=false;                else                {                    if (!sex[a])                        sex[a]=b;   //如果a沒有被標記過,則使a的異性為b                    else                        uni(sex[a],b);  //否則,將a的父節點和b串連                    if (!sex[b])                        sex[b]=a;                    else                        uni(sex[b],a);                }            }        }        if (!ass)            printf("Scenario #%d:\nSuspicious bugs found!\n",p);        else            printf("Scenario #%d:\nNo suspicious bugs found!\n",p);        p++;        cout<<endl;    }    return 0;}

轉載自:http://blog.csdn.net/sio__five/article/details/8813764

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.