POJ2492 A Bug's Life (並查集)

來源:互聯網
上載者:User

標籤:演算法   並查集   poj   

本文出自:http://blog.csdn.net/svitter


題意:

給出昆蟲編號,看昆蟲能否交配,如果出現同性交配或者自我交配的情況,則出現BUG。

輸入輸出分析:

1.輸入輸出資料:

input:

23 31 22 31 34 21 23 4

output:

Scenario #1:Suspicious bugs found!Scenario #2:No suspicious bugs found!

第一行給出的是測試資料的個數,隨後跟著n, m。n是昆蟲個數,m是關係個數。%d %d表示兩個編號的昆蟲進行交配。

輸出資料中間存在空行。

*判斷出BUG以後,繼續讀入測試資料。


題目分析:

這道題目和1291類似,但是相對簡單。

可以如此想。

開一個N*2的數組,前N表示雄性,後N表示雌性。

%d %d分別為i, j 

那麼 i 和 j 一定不屬於同一集合,i+n和j+n一定也不屬於同一集合。

如果屬於同一集合,那麼出現bug。


AC代碼,TIME:829MS

//author: svtter//#include <iostream>#include <stdio.h>#include <string.h>#include <vector>#include <map>#include <algorithm>#include <queue>#include <cmath>#define INF 0xffffffusing namespace std;const int MAXN = 2000011; int root[MAXN];int t;int n, m;void init(){    for(int i = 0; i <= n*2; i++)        root[i] = i;}int getRoot(int i){    if(i == root[i])        return i;    return root[i] = getRoot(root[i]);}void Merge(int i, int j){    int a = getRoot(i);    int b = getRoot(j);    if(a == b)        return;    root[a] = b;}//judge same setbool jud(int i, int j){    return getRoot(i) == getRoot(j);}int main(){    int i, j;    int t1, t2;    bool flag;    cin >> t;    for(i = 1; i <= t; i++)    {        flag = false;        //input        scanf("%d%d", &n, &m);        init();        for(j = 0; j < m; j++)        {            scanf("%d%d",&t1, &t2);            if(flag)                continue;            if(jud(t1, t2) || jud(t1+n, t2+n))                flag = 1;            else            {                Merge(t1, t2+n);                Merge(t1+n, t2);            }        }        //result        printf("Scenario #%d:\n", i);        if(flag)            printf("Suspicious bugs found!\n");        else            printf("No suspicious bugs found!\n");        if(i != t)            printf("\n");    }    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.