带权并查集
需要两个数组,fa[]就是正常的并查集父亲数组
rela[]为当前点与其在并查集中的父亲的关系,0为同性,1为异性
中间的异或操作就是判断两个点的关系是什么
fa[A] fa[B]
x---------------------->y
| |
| |
| |
rela[A] rela[B]
| |
| |
A--------(no edge)------B
由上图可知UNION时fa的异或关系
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 3000
using namespace std;
int kase,n,m,ans;
int fa[MAXN],rela[MAXN];
int Find(int x){
const int f=fa[x];
if(fa[x]!=x){
fa[x]=Find(fa[x]);
rela[x]=rela[x]^rela[f];
}
return fa[x];
}
void UNION(int x,int y,int c,int d){
fa[x]=y;
rela[x]=(rela[c]^rela[d])^1;
}
void solve(){
int a,b;
int i;
for(i=1;i<MAXN;i++){
fa[i]=i;rela[i]=0;
}
for(i=1;i<=m;i++){
scanf("%d%d",&a,&b);
int aa=Find(a),bb=Find(b);
if(!ans && aa!=bb)//different set
UNION(aa,bb,a,b);
else if(!ans && aa==bb && rela[a]==rela[b]){
ans=1;
}
}
}
int main(){
freopen("in.in","r",stdin);
scanf("%d",&kase);
const int u=kase;
while(kase--){
scanf("%d%d",&n,&m);
ans=0;
solve();
printf("Scenario #%d:\n",u-kase);
if(ans)
printf("Suspicious bugs found!\n");
else
printf("No suspicious bugs found!\n");
printf("\n");
}
return 0;
}