1. 程式人生 > >A Bug's Life (並查集)

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