PPOJ 2492 A Bug's Life(分层并查集)

来源:互联网 发布:下载打印机软件 编辑:程序博客网 时间:2024/03/29 19:08

题目链接:
POJ 2492 A Bug’s Life
题意:
有n个昆虫,一般只有性别相异的昆虫才可配对,如果是一只同性恋昆虫,那么它和同性、异性均可配对。
现在给出m组配对关系,问这n个昆虫中是否含有同性恋昆虫?
分析:
由于不知道每只昆虫的性别,那么可以把两种情况都考虑。第i只昆虫性别的反面用i+n表示,
那么对于每对昆虫a,b,要把a和b+n以及a+n和b分别放在同一集合。
当发现a和a+n或者b和b+n同一个集合是那么就出现了同性恋昆虫。

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;const int maxn=2010;int pre[maxn*2],T,n,m,a,b,cases=0;int find(int x){    return pre[x]==x?x:pre[x]=find(pre[x]);}void mix(int x,int y){    int fx=find(x);    int fy=find(y);    if(fx!=fy)    {        pre[fx]=fy;    }}int main(){#ifdef LOCAL    freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);#endif    scanf("%d",&T);    while(T--)    {        scanf("%d%d",&n,&m);        for(int i=0;i<=2*n;i++)            pre[i]=i;        int ok=0;        for(int i=1;i<=m;i++)        {            scanf("%d%d",&a,&b);            if(ok) continue;            mix(a,b+n);            mix(a+n,b);            if(find(a)==find(a+n)||find(b)==find(b+n)) ok=1;        }        printf("Scenario #%d:\n",++cases);        if(ok) printf("Suspicious bugs found!\n");        else printf("No suspicious bugs found!\n");        if(T) printf("\n");    }    return 0;}
0 0