HDU 1829 A Bug's Life

题目大意:告诉你一堆虫子的关系,就是两只相互喜欢,让你找出有没有同性恋的虫子。

题解:加权并查集,感觉比食物链简单很多,难得一次AC,我们直接定义喜欢为异性,记关系d为1,同性为2,r数组记录与祖先的关系,同性或是异性,在线做,当发现新关系与就关系矛盾时,就存在同性恋的虫子。

#include <cstdio> 
using namespace std;
int r[2005],f[2005];
int sf(int x){
    if (f[x]==x) return x;
    else{
        int fx=sf(f[x]);
        r[x]=(r[x]+r[f[x]])%2;
        f[x]=fx;
        return f[x];
    }
}
void U(int x,int y,int fx,int fy,int d){
    f[fy]=fx;
    r[fy]=(2-r[y]+d+r[x])%2;
}
int main(){
    int T,n,m,x,y,fx,fy,cnt=1;
    scanf("%d",&T);
    while(T--){
        bool bo=true;
        printf("Scenario #%d:
",cnt++);
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        {f[i]=i; r[i]=0;}
        for(int i=0;i<m;i++){
            scanf("%d%d",&x,&y);
            fx=sf(x);fy=sf(y);
            if(fx!=fy)U(x,y,fx,fy,1);
            else if((r[y]-r[x]+2)%2!=1){
                if(bo)puts("Suspicious bugs found!
");
                bo=false;
            }
        }
        if(bo)puts("No suspicious bugs found!
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/3543407.html