a404中等帶奇偶關係的可回復並查集
APCS 2021/11:真假子圖 (ZeroJudge g598)
檢查每位調查員是否產生奇環,並在下一位之前完整回復原圖狀態。
這題在學什麼
把組別看成 0 或 1,每條合作邊 (a,b) 都要求 color[a] XOR color[b]=1。並查集另外保存每個節點與父節點的組別差 parity;沿父鏈 XOR 即可得到節點相對根的組別。若 a、b 同根,便直接檢查兩者的差是否為 1;不符合就是矛盾。
若根不同,要把其中一根接到另一根,根與根之間所需的差為 parity(a) XOR parity(b) XOR 1。按集合大小合併,使樹高 O(log n)。每次合併記錄被接上的根、接收根與接收根的舊大小,便可倒序撤銷。不能做未記錄的路徑壓縮,否則回復會遺漏父鏈改動。
先加入原有 m 對,再清空這一階段的合併紀錄,固定原圖為基底。每位調查員從同一基底加入自己的 k 對;發現矛盾後仍須讀完該人的輸入,接著撤銷此次所有合併。如此不同調查員不會互相影響,且每次檢查等價於在原圖上判斷可否二分組。
Step-by-step animation
公開範例二:三位調查員各自回到原圖
步驟 1 / 4
原圖推出 0 與 2 同組
原有邊為 0–3、2–3,故可令 0=2=0、3=1;1、4 尚獨立。
0:組0
2:組0
3:組1
1:未定
4:未定
- 固定關係
- 0 XOR 2=0
#include <bits/stdc++.h>
using namespace std;
struct RollbackDSU {
vector<int> parent, size, parity;
vector<array<int, 3>> history;
explicit RollbackDSU(int n) : parent(n), size(n, 1), parity(n, 0) {
iota(parent.begin(), parent.end(), 0);
}
pair<int, int> find(int x) {
int difference = 0;
while (parent[x] != x) {
difference ^= parity[x];
x = parent[x];
}
return {x, difference};
}
bool add(int a, int b) {
auto [ra, pa] = find(a);
auto [rb, pb] = find(b);
if (ra == rb) return (pa ^ pb) == 1;
if (size[ra] < size[rb]) swap(ra, rb);
history.push_back({rb, ra, size[ra]});
parent[rb] = ra;
parity[rb] = pa ^ pb ^ 1;
size[ra] += size[rb];
return true;
}
void rollback() {
while (!history.empty()) {
auto change = history.back();
history.pop_back();
int child = change[0], root = change[1];
parent[child] = child;
parity[child] = 0;
size[root] = change[2];
}
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
RollbackDSU dsu(n);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
dsu.add(a, b);
}
dsu.history.clear();
int p, k;
cin >> p >> k;
for (int id = 1; id <= p; ++id) {
bool bad = false;
for (int j = 0; j < k; ++j) {
int a, b;
cin >> a >> b;
if (!bad && !dsu.add(a, b)) bad = true;
}
if (bad) cout << id << '\n';
dsu.rollback();
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。