【带权并查集】A Bug's Life POJ - 2492
A Bug's Life POJ - 2492
题意:
一种昆虫,异性之间才能配对,同性之间不能配对。现给出\(n\)只昆虫的\(m\)条配对关系,问其中有没有不合理(即同性配对)的情况。
思路:
虽然看起来迥异,但这题的内在逻辑和Parity game POJ - 1733是一样的……所以公式可以照搬,都是异或运算。具体推导表格可以直接看那一题的题解。
const int maxn = 200000 + 100;
int n, m;
int rela[maxn], fa[maxn];
int find(int x) {
if (fa[x] == -1) return x;
int tmp = find(fa[x]);
rela[x] = rela[x] ^ rela[fa[x]];
return fa[x] = tmp;
}
bool merge(int u, int v, int s) {
int r1 = find(u);
int r2 = find(v);
if (r1 == r2) {
return s == rela[u] ^ rela[v];
}
else {
fa[r1] = r2;
rela[r1] = rela[u] ^ rela[v] ^ s;
return true;
}
}
int main()
{
//ios::sync_with_stdio(false);
int t; cin >> t; for (int kase = 1; kase <= t; kase++) {
n = read(); m = read();
for (int i = 1; i <= n; i++) fa[i] = -1;
memset(rela, 0, sizeof(rela));
int ok = 1;
for (int i = 1; i <= m; i++) {
int u, v;
u = read(); v = read();
if (!ok) continue;
if (!merge(u, v, 1)) ok = 0;
}
if (kase != 1) printf("\n");
printf("Scenario #%d:\n", kase);
if (ok) printf("No suspicious bugs found!\n");
else printf("Suspicious bugs found!\n");
}
return 0;
}