POJ 2492 A Bug's Life 并查集的应用

来源:互联网 发布:淘宝直播怎么加入 编辑:程序博客网 时间:2024/06/11 04:53

A Bug's Life
Time Limit: 10000MS
Memory Limit: 65536KTotal Submissions: 24838
Accepted: 8088

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

23 31 22 31 34 21 23 4

Sample Output

Scenario #1:Suspicious bugs found!Scenario #2:No suspicious bugs found!

Hint

Huge input,scanf is recommended.

Source

TUD Programming Contest 2005, Darmstadt, Germany

这一题可以用深度优先搜索,也可以用并查集。并查集似乎更简单方便些。

代码如下:

#include <iostream>#include <fstream>using namespace std;const int maxn = 2010;int parent[maxn];bool gen[maxn];//gen[k]表示子节点与双亲节点性别是否相同,1表示相同,0表示不同int find(int k){    if(parent[k]<0)        return k;    int t = find(parent[k]);    gen[k]=gen[k]?gen[parent[k]]:!gen[parent[k]];//根据双亲节点的性别,更改子节点的性别    parent[k]=t;    return t;}bool merge(int a,int b){    int l = find(a);    int r = find(b);    if(l==r)    {        if(gen[a]==gen[b])//判断性别是否相同            return false;        else            return true;    }    if(gen[a]==gen[b])//如果a,b的性别状态相同,则其双亲性别相反        gen[r]=false;    parent[r]=l;    return true;}int main(){    freopen("in.txt","r",stdin);    int cn,t=0;    scanf("%d",&cn);    while(cn--)    {        int n,m,a,b;        bool flag = true;//无有悖论出现的标志        scanf("%d%d",&n,&m);        for(int i=1;i<=n;i++)            gen[i]=true,parent[i]=-1;        while(m--)        {            scanf("%d%d",&a,&b);            if(flag)                flag=merge(a,b);        }        printf("Scenario #%d:\n",++t);        if(flag)            printf("No suspicious bugs found!\n\n");        else            printf("Suspicious bugs found!\n\n");    }}



原创粉丝点击