poj 2492 A Bug's Life 并查集

题意:N的虫里面有M对情侣关系,判断其中存不存在“基情”,即在之前确定的异性关系中出现了同性的情侣。

分析:我们可以假设异性在不同的并查集里,那么假设有一对情侣a和b是异性关系,那么a和b的异性是同性关系,b和a的异性也是同性关系,即a和b的异性 以及 b和a的异性 在同一个并查集里。为了模拟这个过程,我们假设对于任意一个元素c , c+n是他的默认异性,接下来每一次合并之前判断有没有矛盾就行了。

View Code
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
#define re(i,n) for(int i=0;i<n;i++)
#define re1(i,n) for(int i=1;i<=n;i++)
const int maxn = 4040;
int p[maxn];
int n , m;
inline void init() { re(i,maxn) p[i] = i; }
int find(int x) { return x == p[x] ? x : p[x] = find(p[x]); }
void Union(int x , int y) {
    int a = find(x) , b = find(y);
    p[a] = p[b] = p[x] = p[y] = min(a,b);
}
int main() {
    int T;
    scanf("%d",&T);
    re1(cas,T) {
        scanf("%d%d",&n,&m);
        init();
        int ok = 1;
        while(m--) {
            int u , v;
            scanf("%d%d",&u,&v);
            if(!ok) continue;
            if(find(u) == find(v)) ok = 0;
            else Union(u,v+n) , Union(v,u+n);
        }
        printf("Scenario #%d:\n",cas);
        printf(!ok ? "Suspicious bugs found!\n" : "No suspicious bugs found!\n");
        if(cas != T) printf("\n");
    }
    return 0;
}
posted @ 2012-07-05 03:28  lenohoo  阅读(185)  评论(0编辑  收藏  举报