File tree Expand file tree Collapse file tree 1 file changed +11
-7
lines changed Expand file tree Collapse file tree 1 file changed +11
-7
lines changed Original file line number Diff line number Diff 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-
4953struct OfflineDynamicConnectivity {
5054 int n;
5155 UndoableUnionFind uf;
You can’t perform that action at this time.
0 commit comments