poj 2492 A Bug's Life【带权并查集】

就是给一个无向图判是否有奇环
用带权并查集来做,边权1表示连接的两个节点异性,否则同性,在%2意义下进行加法运算即可,最后判相同的时候也要%2,因为可能有负数

#include<iostream>
#include<cstdio>
using namespace std;
const int N=1000005;
int T,n,m,f[N],s[N];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
int zhao(int x)
{
    if(x==f[x])
        return x;
    int nw=zhao(f[x]);
    s[x]=(s[f[x]]+s[x])%2;
    return f[x]=nw;
}
int main()
{
    T=read();
    for(int cas=1;cas<=T;cas++)
    {
        n=read(),m=read();
        for(int i=1;i<=n;i++)
            f[i]=i,s[i]=0;
        bool ok=1;
        while(m--)
        {
            int x=read(),y=read(),fx=zhao(x),fy=zhao(y);
            if(fx!=fy)
            {
                f[fy]=fx;
                s[fy]=(s[y]-s[x]+1)%2;
            }
            else if((s[y]-s[x])%2==0)
                ok=0;
            // for(int i=1;i<=n;i++)
                // cerr<<f[i]<<" ";
            // cerr<<endl;
        }
        printf("Scenario #%d:\n",cas);
        if(ok)
            printf("No suspicious bugs found!\n\n");
        else
            printf("Suspicious bugs found!\n\n");
    }
    return 0;
}

转载于:https://www.cnblogs.com/lokiii/p/9968382.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值