之前也写过两次带权并查集,但是并没有理解新开那个记录权值的数组的意义,不知怎么当时都歪打正着把题给(凭人品)做出来了。今天又按照以前错误的想法去做带权并查集,果不其然一下子就做错了。于是虚心学习,了解到新开的那个数组是用来记录当前节点和祖先结点的关系的。于是更新了一下合并和路径压缩用的公式,把题交上了。
#include<iostream>
#include<cstdio>
#include<string.h>
#include<algorithm>
using namespace std;
int t,n,m,fa[2010],sex[2010];
int find(int x)
{
int fx=fa[x];
if (fa[x]!=x)
{
fx=find(fa[x]);
sex[x]=sex[fa[x]]^sex[x];
}
return fa[x]=fx;
}
bool u(int x,int y)
{
int fx=find(x); int fy=find(y);
if (fx!=fy)
{
fa[fy]=fx;
sex[fy]=(sex[x]+sex[y]+1)%2;
}else
{
if (sex[x]==sex[y]) return false;
}
return true;
}
int main()
{
scanf("%d",&t);
int cas=0;
while (t--)
{
cas++;
scanf("%d%d",&n,&m);
for (int i=1; i<=n; i++)
{
fa[i]=i; sex[i]=0;
}
bool flag=true;
for (int i=1; i<=m; i++)
{
int a,b; scanf("%d%d",&a,&b);
if (!u(a,b)) flag=false;
}
printf("Scenario #%d:\n",cas);
if (flag) printf("No suspicious bugs found!\n\n");
else printf("Suspicious bugs found!\n\n");
}
return 0;
}