【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;
}

猜你喜欢

转载自blog.csdn.net/qq_39826163/article/details/82987134