POJ 2492 A Bug's Life

来源:互联网 发布:有好看衣服的淘宝店铺 编辑:程序博客网 时间:2024/05/20 09:24

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.


【题目分析】
带偏移量的并查集。维护一个数组d来表示和跟的关系(能否进行基因交流)。然后就是类似于并查集的合并与查询。


【代码】

#include <cstdio>#include <cstring>int f[2001],d[2001];int gf(int k){    int t=f[k];    if (t==k) return k;    f[k]=gf(t);    d[k]=(d[k]+d[t])%2;    return f[k];}void un(int a,int b){    int x=gf(a),y=gf(b);    if (x==y) return;    f[x]=y;    d[x]=((d[a]-d[b])^1);}int main(){    int T,flag=1,kase=0;    scanf("%d",&T);    while (T--)    {        flag=1;        int n,m;        scanf("%d%d",&n,&m);        for (int i=1;i<=n;++i) f[i]=i,d[i]=0;        for (int i=1;i<=m;++i)        {            int a,b;            scanf("%d%d",&a,&b);            if (gf(a)==gf(b))              {if (d[a]!=(d[b]^1)) flag=0;}            else un(a,b);        }        if(flag)printf("Scenario #%d:\nNo suspicious bugs found!\n\n",++kase);        else printf("Scenario #%d:\nSuspicious bugs found!\n\n",++kase);    }}
0 0
原创粉丝点击