1. 程式人生 > >【ZCMU1437】A Bug's Life(種類並查集)

【ZCMU1437】A Bug's Life(種類並查集)

題目連結

1437: A Bug's Life

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 113  Solved: 50
[Submit][Status][Web Board]

Description

 

 

Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs. Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.

 

Input

 

 

The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least 1, and up to 2000) and the number of interactions (up to 5000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.

 

Output

 

 

The output for every scenario is a line either "No suspicious bugs found!" if the experiment is consistent with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's assumption is definitely wrong.

 

Sample Input

2

3 3

1 2

2 3

1 3

4 2

1 2

3 4

Sample Output

Suspicious bugs found!

No suspicious bugs found!

HINT

 

Source

POJ

 

【題意】

兩隻昆蟲A和B如果是異性他們能在一起玩,如果是同性就不能在一起玩,給定m組資料,判斷資料中是否有一組資料出錯(即不能一起玩的一起玩了),如果有出錯資料則輸出“Suspicious bugs found! ”,反之則輸出“No suspicious bugs found!”。

 

【解題思路】

我們用pre[i]表示i的父親,用sum[i]表示i與他父親的關係,0表示同性,1表示異性。當兩隻昆蟲的父親相同時,需要判斷一下他們與父親的關係,如果一樣則說明兩隻昆蟲是同性。當兩隻昆蟲的父親不同時,需要建立祖先關係,因為兩隻昆蟲是異性,所以A->B為1。

【程式碼】

#include<bits/stdc++.h>
using namespace std;
const int maxn=2e3+5;
int pre[maxn],sum[maxn];
int findroot(int x)
{
    if(x!=pre[x])
    {
        int r=pre[x];
        pre[x]=findroot(pre[x]);
        sum[x]=(sum[x]+sum[r]+1)%2;
    }
    return pre[x];
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,m,flag=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)pre[i]=i;
        while(m--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            int fx=findroot(x);
            int fy=findroot(y);
            if(fx!=fy)
            {
                pre[fx]=fy;
                sum[fx]=(sum[y]-sum[x]+1)%2;
            }
            else
            {
                if(sum[x]==sum[y])flag=1;
            }
        }
        if(flag)printf("Suspicious bugs found!\n");
        else printf("No suspicious bugs found!\n");
    }
    return 0;
}