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;
}

猜你喜欢

转载自www.cnblogs.com/lokiii/p/9968382.html