n 隻蟲子,m 對交互記錄 (a,b) 表示 a 和 b 異性交互。判斷是否存在矛盾(即某對同性交互)。蟲子編號 1~n,n≤2000, m≤1e6。
維護兩類關係:
對每對 (a,b):
#include
#include
const int MAXN = 2005;
int fa[MAXN], sex[MAXN];
int find(int x) {
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void unite(int x, int y) {
x = find(x); y = find(y);
if (x != y) fa[x] = y;
}
int main() {
int T; scanf("%d", &T);
for (int tc = 1; tc <= T; tc++) {
int n, m; scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) { fa[i] = i; sex[i] = 0; }
bool suspicious = false;
for (int i = 0; i < m; i++) {
int a, b; scanf("%d%d", &a, &b);
if (suspicious) continue;
int fa_a = find(a), fa_b = find(b);
if (fa_a == fa_b) { suspicious = true; continue; }
if (sex[a] == 0) sex[a] = b; else unite(sex[a], b);
if (sex[b] == 0) sex[b] = a; else unite(sex[b], a);
}
printf("Scenario #%d:\n", tc);
puts(suspicious ? "Suspicious bugs found!" : "No suspicious bugs found!");
if (tc != T) printf("\n"); // 題目要求場景間空行
}
return 0;
}