POJ 2492 A Bug's Life

并查集确定昆虫的关系,题意有点BT...用一个数组rel代表与其父节点的关系,为0则代表相同,为1代

表不同。如果两者不在一个集合中则合并,在一个集合中则判断种类是否相同,相同则存在同性恋的虫子。

/*Accepted    164K    766MS    C++    1224B    2012-08-24 09:28:15*/

#include<stdio.h>

#include<string.h>

#include<stdlib.h>



const int MAXN = 1 << 11;

int p[MAXN], rel[MAXN];



int find_set(int x)

{

    int t;

    if(x != p[x])

    {

        t = p[x];

        p[x] = find_set(p[x]);

        rel[x] = (rel[x] + rel[t]) & 1;

    }

    return p[x];

}



int main()

{

    int cas, T;

    int x, y, n, m, i;

    bool flag;

    scanf("%d", &T);

    for(cas = 1; cas <= T; cas ++)

    {

        scanf("%d%d", &n, &m);

        for(i = 1; i <= n; i ++)

        {

            p[i] = i, rel[i] = 0;

        }

        flag = false;

        while(m --)

        {

            scanf("%d%d", &x, &y);

            int nx, ny;

            nx = find_set(x), ny = find_set(y);

            if(nx != ny)

            {

                p[ny] = nx;

                rel[ny] = (rel[y] + rel[x] + 1) & 1;

            }

            else

            {

                if(rel[x] == rel[y])

                    flag = true;

            }

        }

        printf("Scenario #%d:\n", cas);

        if(flag)

            printf("Suspicious bugs found!\n");

        else

            printf("No suspicious bugs found!\n");

        printf("\n");

    }

    return 0;

}

 

 

你可能感兴趣的:(life)