pku 2492 A Bug's Life (并查集应用)

http://poj.org/problem?id=2492

题意:

专家研究一种病毒,发现他们只与异性发生性关系。问题:查看他们是否具有同性恋关系,给出n个病毒编号从1-n,给出q中关系,每种关系x,y表示x与y有性行为,即表示他们属于异性,输出这群病毒是否具有异性关系。

思路:

并查集的基本作用是用来区分不同的集合关系,相同的加入同一集合,不同的则不处理。这里给出x,y的不同关系,让你判断是否是相同集合,这里我们只要把相同的合并即可,另开一个数组记录与x不同的集合的代表(只要一个点即可代表整个与x不同的集合),只要遇到x,y不同我们就把x与opt[y] y与opt[x]合并即可,这样属于同一集合的点就是同性了,最后检查给出的x,y是否属于同性即可。

View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#define maxn 100007
using namespace std;

int f[maxn],opt[maxn];

void init(int len)
{
    for (int i = 0; i <= len; ++i)
    {
        f[i] = i;
        opt[i] = 0;
    }
}
int find(int x)
{
    if (f[x] != x)
    f[x] = find(f[x]);
    return f[x];
}
void Union(int x,int y)
{
    x = find(x);
    y = find(y);
    if (x != y) f[x] = y;
}
int main()
{
   // freopen("d.txt","r",stdin);
    int t,n,q,x,y;
    int cas = 1;
    scanf("%d",&t);
    while (t--)
    {
        bool flag = false;
        scanf("%d%d",&n,&q);
        init(n);
        while (q--)
        {
            scanf("%d%d",&x,&y);
            if (!flag)
            {
                int xi = find(x);
                int yi = find(y);
                if (xi == yi) flag = true;
                else
                {
                    if (opt[x] == 0) opt[x] = y;
                    Union(opt[x],y);
                    if (opt[y] == 0) opt[y] = x;
                    Union(x,opt[y]);
                }
            }
        }
         printf("Scenario #%d:\n",cas++);
        if (flag) printf("Suspicious bugs found!\n");
        else printf("No suspicious bugs found!\n");
        printf("\n");
    }
    return 0;
}

 

同类型题目:

http://www.cnblogs.com/E-star/archive/2011/11/27/2264781.html

posted @ 2012-07-31 10:10  E_star  阅读(186)  评论(0编辑  收藏  举报