题意:T组测试数据,每组数据有一个N,M表示N个人和M个关系,下面M行为关系,每组关系有两个数字a,b表示a喜欢b,问有没有同性恋?
思路:带权并查集。权值0表示和父节点为同性,1为异性。
//#include<bits/stdc++.h>
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN = 40005;
int n, m, f[MAXN], w[MAXN];
bool flag;
void init()
{
flag = false;
for (int i = 0; i <= n; i++)
{
f[i] = i; w[i] = 0;
}
}
int Find(int x)
{
if (f[x] == x) return x;
int t = f[x];
f[x] = Find(f[x]);
w[x] = (w[x] + w[t]) % 2;
return f[x];
}
void Union(int a, int b)
{
int root1 = Find(a), root2 = Find(b);
if (root1 != root2)
{
f[root1] = root2;
w[root1] = (w[b] + 1 - w[a] + 2) % 2;
}
else
{
if ((w[a] - w[b] + 2) % 2 == 0) flag = true;
}
}
int main()
{
int T, CASE = 1;
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
init();
for (int i = 0; i < m; i++)
{
int a, b;
scanf("%d%d", &a, &b);
Union(a, b);
}
printf("Scenario #%d:\n", CASE++);
if (flag) printf("Suspicious bugs found!\n");
else printf("No suspicious bugs found!\n");
if (T) printf("\n");
}
return 0;
}
/*
2
3 3
1 2
2 3
1 3
4 2
1 2
3 4
*/