维护一个relation数组,保留着此元素和根元素之间的性别关系。之后就可以判断gay了。
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn=2010; int T,n,m; int fa[maxn],rela[maxn]; int Find(int x) { int t; if(fa[x] == x) return x; t = fa[x]; fa[x] = Find(fa[x]); rela[x] = (rela[x]+rela[t]+1)%2; return fa[x]; } void Union(int x,int y) { int fx=Find(x),fy=Find(y); fa[fx] = fy; rela[fx] = (rela[y]-rela[x])%2; } int main() { scanf("%d",&T); for(int kase=1;kase<=T;kase++) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { fa[i] = i; rela[i] = 1; } int x,y,sus=0; for(int i=0;i<m;i++) { scanf("%d%d",&x,&y); if(Find(x) == Find(y)) { if(rela[x] == rela[y]) sus=1; } else Union(x,y); } printf("Scenario #%d:\n",kase); if(sus) printf("Suspicious bugs found!\n\n"); else printf("No suspicious bugs found!\n\n"); } }