Skip to content

Commit 4fdac82

Browse files
author
Takanori MAEHARA
authored
debug
incorrect implementation of undoable union find. (path compression cannot be undo)
1 parent 3a44bc1 commit 4fdac82

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

data_structure/union_find_undo.cc

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,29 @@ struct UndoableUnionFind {
2727
UndoableUnionFind(int n) : parent(n, -1) { };
2828
bool unite(int u, int v) {
2929
u = root(u); v = root(v);
30-
if (u == v) return false;
31-
if (parent[u] > parent[v]) swap(u, v);
32-
history.push_back(make_tuple(u, v, parent[v]));
33-
parent[u] += parent[v]; parent[v] = u;
34-
return true;
30+
if (u == v) {
31+
history.push_back(make_tuple(-1,-1,-1));
32+
return false;
33+
} else {
34+
if (parent[u] > parent[v]) swap(u, v);
35+
history.push_back(make_tuple(u, v, parent[v]));
36+
parent[u] += parent[v]; parent[v] = u;
37+
return true;
38+
}
3539
}
3640
void undo() {
3741
int u, v, w;
3842
tie(u, v, w) = history.back();
3943
history.pop_back();
44+
if (u == -1) return;
4045
parent[v] = w;
4146
parent[u] -= parent[v];
4247
}
4348
bool find(int u, int v) { return root(u) == root(v); }
44-
int root(int u) { return parent[u] < 0 ? u : parent[u] = root(parent[u]); }
49+
int root(int u) { while (parent[u] >= 0) u = parent[u]; return u; }
4550
int size(int u) { return -parent[root(u)]; }
4651
};
4752

48-
4953
struct OfflineDynamicConnectivity {
5054
int n;
5155
UndoableUnionFind uf;

0 commit comments

Comments
 (0)