A Bug's Life(POJ - 2492)种类并查集

一、题目大意

给出n只虫子,不同性别的虫子可以在一起,相同性别的虫子不可以在一起。

给m对虫子,看有没有同性别的虫子在一起。


二、题目分析

种类并查集,同性是0,异性是1.

难点处分析:

对于不同集合的合并,即Unite()函数的编写,我们用向量的偏移来理解。


对于本题来说 w就是1,因为x和y必然是异性。

三、附代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<queue>
#include<cstring>
#include<string>
#include<set>
#include<cmath>
#include<map>
#include<sstream>
using namespace std;
#define MOD 1000000007
#define inf 0x3f3f3f3f
typedef long long LL;
const int maxn = 2000 + 8;

int t,n,m,par[maxn],ran[maxn],x,y;
bool flag;

void Init()
{
    flag = true;
    for(int i = 0 ; i < maxn; ++i){
        par[i] = i;
        ran[i] = 0;
    }
}
int Find(int x)
{
    if(x == par[x]) return x;
    int tmp = par[x];
    par[x] = Find(tmp);
    ran[x] = (ran[x] + ran[tmp]) % 2;
    return par[x];
}
void Unite(int x,int y)
{
    int rootx = Find(x);
    int rooty = Find(y);
    if(rootx == rooty) {
        if (ran[x] == ran[y]) {
            flag = false;
            return;
        }
    }else {
        par[rootx] = rooty;
        ran[rootx] = (ran[y] + 1  - ran[x]) % 2;
    }
}
int main()
{
    int kase = 0;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        Init();
        kase++;
        for(int i = 0; i < m; ++i){
            scanf("%d%d",&x,&y);
            if(!flag) continue;
            Unite(x,y);
        }
        cout << "Scenario #" << kase << ":" << endl;
        if(flag){
            cout << "No suspicious bugs found!" << endl << endl;
        }else{
            cout << "Suspicious bugs found!" << endl << endl;
        }
    }
    return 0;
}
/*
2
3 3
1 2
2 3
1 3
4 2
1 2
3 4
*/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值