HDU 1829 A Bug's Life

来源:互联网 发布:手机版特效软件 编辑:程序博客网 时间:2024/05/22 17:38

博士要研究一种虫子是不是不分雌雄。它做了很多研究,每只虫子都有标号,他记录了所有交配的虫子的标号。问这种虫子是不是不分雌雄。
做法:用并查集,再开一个sex数组,sex[a] = b代表第一个跟a交配的是b;

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace std;int fa[2222],sex[2222];void init(int x){    for(int i = 0 ; i <= x ;i++)        fa[i] = i;}int getfa(int x){    return fa[x] == x ? x : fa[x] = getfa(fa[x]);}int main(){    int t;    scanf("%d",&t);    for(int cas = 1 ; cas <= t ; cas++)    {        memset(sex,0,sizeof(sex));        printf("Scenario #%d:\n",cas);        int n,m;        bool flag = true;        scanf("%d%d",&n,&m);        init(n);        for(int i = 1 ; i <= m ; i++)        {            int a,b;            scanf("%d%d",&a,&b);            if(!sex[a]&&!sex[b])            {                sex[a] = b;                sex[b] = a;            }            else if(!sex[a]&&sex[b])            {                sex[a] = b;                if(getfa(sex[b]) != getfa(a))                    fa[getfa(a)] = getfa(sex[b]);            }            else if(sex[a]&&!sex[b])            {                sex[b] = a;                if(getfa(sex[a]) != getfa(b))                    fa[getfa(b)] = getfa(sex[a]);            }            else if(sex[a]&&sex[b])            {                if(getfa(sex[b]) != getfa(a))                    fa[getfa(a)] = getfa(sex[b]);                if(getfa(sex[a]) != getfa(b))                    fa[getfa(b)] = getfa(sex[a]);            }            if(getfa(a) == getfa(b)) flag = false;        }        if(flag) printf("No suspicious bugs found!\n");        else printf("Suspicious bugs found!\n");        printf("\n");    }    return 0;}
0 0