POJ 2492 A Bug's Life

老样子,经典的并查集题目,和Find them,catch them几乎一样的做法,只不过增加了一个判断,在两个结点的父节点相同的时候判断一下他们俩的新关系和原有的关系是否有矛盾;

另外注意即使有矛盾也不能提前跳出循环,因为还有很多数据要输入= =

#include <iostream>
#include <cstdio>
#include <memory.h>
using namespace std;

#define maxn 2050

struct node{
    int fa;
    int re;
};

node bugs[maxn]={0};

int findfa(int a){
    if(bugs[a].fa == a)
        return a;
    int temp = bugs[a].fa;
    bugs[a].fa = findfa(temp);
    bugs[a].re ^= bugs[temp].re;
    return bugs[a].fa;
}

bool insert(int arg1,int arg2){
    int fa1 = findfa(arg1);
    int fa2 = findfa(arg2);
    if(fa1 != fa2){
        bugs[fa2].fa = fa1;
        bugs[fa2].re = !(bugs[arg1].re^bugs[arg2].re); 
        return true;
    }
    else{
        if(bugs[arg1].re == bugs[arg2].re){
            return false;
        }
        else
            return true;
    }
}

int main(){
    int t;
    scanf("%d",&t);
    for(int j=1;j<=t;++j){
        int n,m;
        memset(bugs,0,sizeof(bugs));
        scanf("%d%d",&n,&m);

        for(int i=1;i<=n;++i){
            bugs[i].fa = i;
        }

        bool found = false;
        while(m--){
            int arg1,arg2;
            scanf("%d%d",&arg1,&arg2);
            if(!found && !insert(arg1,arg2)){
                found = true;
            }
        }
        printf("Scenario #%d:\n",j);

        if(!found){
            printf("No suspicious bugs found!\n\n");
        }
        else{
            printf("Suspicious bugs found!\n\n");
        }
    }
    //system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值