poj2492(加权值的并查集)

Description

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!

Hint

Huge input,scanf is recommended.

题目意思有点bt,就是正常昆虫是异性交配,输入一对就代表这一对交配了,让你看这一群昆虫是否有同性恋!

加权值的并查集题目,刚开始会有些不好理解,相当于把有过关系的所有虫子联系在一起,这样才有可能发现是否是同性恋,而且我们处理这种题目的办法都是将每个子节点与父节点作比较(这个比方就好比我们确定任何事物的方式一样,就是先找参照物!!找到参照物了自然关系明了),用一个rela数组来记录,用0,1来表示与父节点是同性还是异性,那么自然就好比较两个昆虫是否有同性恋情节了。相当于在并查集的原形之上加了一个权值,怎样记录权值的变化就成了这题的关键!


#include <iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int MAXN = 100010;

int f[MAXN],rela[MAXN];

int ff(int x)
{
    int tem=f[x];
    if(tem!=x)
    f[x]=ff(tem),rela[x]=(rela[x]+rela[tem])%2;
    return f[x];
}
void join(int a,int b)
{
    int tem1=ff(a),tem2=ff(b);
    f[tem1]=tem2;
    rela[tem1]=((rela[a]-rela[b]+1)%2);
}
int main()
{
    int t,o=1;scanf("%d",&t);
    while(t--)
    {
        int n,m,b,c;
        scanf("%d%d",&n,&m);
        for(int i=0;i<=MAXN;i++)
        f[i]=i,rela[i]=0;
        int flag=0;
        while(m--)
        {
            scanf("%d%d",&b,&c);
            if(flag==0&&ff(b)!=ff(c))
            join(b,c);
            else if(flag==0&&ff(b)==ff(c)&&rela[b]==rela[c])
            flag=1;
        }
    if(flag==0)
    {
        printf("Scenario #%d:\n",o++);
        printf("No suspicious bugs found!\n\n");
    }else
    {
        printf("Scenario #%d:\n",o++);
        printf("Suspicious bugs found!\n\n");
    }
    }
    return 0;
}


posted @ 2015-08-10 14:19  martinue  阅读(1139)  评论(0编辑  收藏  举报