A Bug's Life (并查集)

     Background
    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.

    Problem
    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 one, and up to 2000) and the number of interactions (up to 1000000) 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 containing "Scenario #i:", where i is the number of the scenario starting at 1, followed by one line saying 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

    Scenario #1:
    Suspicious bugs found!

    Scenario #2:
    No suspicious bugs found!


题意:首先输入n表示虫子的个数,然后输入m,表示接下来有m行信息,比如第i行输入a,b,表示a和b异性,让判断在给出的实例中有没有同性的。

分析:我们可以这样思考,a b存在恋爱关系,表示他们是异性,之间相互矛盾,用集合A表示与a是相同性别 的元素,集合B表示与a是不同性别的元素,这样的话a放在A集合,a+n(表示与a相异的性别)放在B集合,b放在B集合,b+n放在 A集合。如果在统计时发现,a和a+n或是b和b+n在相同的集合里面就是出现了矛盾的情况,即存在同性恋,反之,不存在。

#include<stdio.h>
#include<string.h>

#define MAXN 1000000
int f[MAXN*2];//开一个大一点的数组,前面的存储一个性别的,后面的再存储一个性别的
int getf(int v)
{
	if(f[v] == v)
		return v;
	else
	{
		f[v] = getf(f[v]);
		return f[v];
	}
}
void merge(int v, int u)
{
    int t1 = getf(v);
    int t2 = getf(u);
    if(t1 != t2)
        f[t2] = t1;
    return ;
}
int main()
{
    int i,t,x,y,n,m,flag,count=1;
    scanf("%d", &t);
    while(t --)
    {
    	flag = 1;
    	for(i = 1; i <= 2*MAXN; i ++)
            f[i] = i;
        scanf("%d%d",&n,&m);
        for(i = 1; i <= m; i ++)
        {
	        scanf("%d%d",&x,&y);
	        if(flag == 0)//已经找到性别相同的
	            continue;
	        if(getf(x) == getf(y) || getf(x+MAXN) == getf(y+MAXN))//根节点一样,性别相同
	        {
	            flag = 0;
	            continue;
	        }
	        else
	        {
	            merge(x, y+n);
	            merge(x+n, y);
	        }
        }
        printf("Scenario #%d:\n", count ++);
        if(flag == 0)
            printf("Suspicious bugs found!\n\n");
        else
            printf("No suspicious bugs found!\n\n");
	}
    return 0;
}

猜你喜欢

转载自blog.csdn.net/queen00000/article/details/81481682