/
ContractionTopTree.hpp
528 lines (465 loc) · 16.8 KB
/
ContractionTopTree.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// TopTreeLibrary Copyright (C) 2022 Lukáš Ondráček <ondracek.lukas@gmail.com>, use under MIT license
#ifndef CONTRACTION_TOP_TREE_HPP
#define CONTRACTION_TOP_TREE_HPP
#include "TopTree.hpp"
#include <cstdint>
#ifdef TOP_TREE_INTEGRITY
#include "tests/ContractionTopTreeIntegrity.hpp"
#else
namespace TopTreeInternals {
template <class... TUserData> class ContractionTopTreeIntegrity {};
}
#define ttassert(cond)
#endif
namespace TopTreeInternals {
template <class... TUserData>
class ContractionTopTree : public TopTree<TUserData...> {
protected:
using Integrity = typename TopTree<TUserData...>::Integrity;
using EIntegrity = ContractionTopTreeIntegrity<TUserData...>; friend EIntegrity;
public:
#ifdef TOP_TREE_INTEGRITY
virtual void testIntegrity() { // just root tree test
Integrity::treeConsistency(ext(this->exposedRoot));
this->rollback();
EIntegrity::treeConsistency(ext(this->exposedRoot));
}
#endif
virtual void link(Vertex u, Vertex v, TUserData... userData);
virtual std::tuple<TUserData...> cut(Vertex u, Vertex v);
private:
using Node = typename TopTree<TUserData...>::Node;
struct VirtNode;
struct Arc { // circular dequeue, always stored in VirtNode.arcs array with its twin
enum Dir {PRED = 0, SUCC = 1};
private:
friend EIntegrity;
Arc *ptrs[2]; // pred, succ
public:
VirtNode *const virtNode;
size_t arcIndex() { return virtNode->arcs != this; }
Arc *pred() { return ptrs[PRED]; }
Arc *succ() { return ptrs[SUCC]; }
Arc *get(int dir) { return ptrs[dir]; }
Arc *twin() { return &virtNode->arcs[!arcIndex()]; }
Arc(VirtNode *virtNode) : virtNode(virtNode) {
ptrs[0] = ptrs[1] = twin();
}
// Initializes arc as leaf
void initLeaf() {
ptrs[SUCC] = twin();
ptrs[SUCC]->ptrs[PRED] = this;
}
// Connects (possibly uninitialized) this to tour given by its new succ arc
void connectToTour(Arc *arc) {
ptrs[SUCC] = arc;
twin()->ptrs[PRED] = arc->ptrs[PRED];
arc->ptrs[PRED]->ptrs[SUCC] = twin();
arc->ptrs[PRED] = this;
}
// Disconnects this from its succ leaving this->ptrs inconsistently unchanged
void disconnectFromTour() {
ptrs[SUCC]->ptrs[PRED] = twin()->ptrs[PRED];
ptrs[SUCC]->ptrs[PRED]->ptrs[SUCC] = ptrs[SUCC];
}
// Sets pred/succ to given arc on lower level, marking the pointer
template <Dir D>
void setMarked(Arc *orig) { // call upgradeIfMarked() before using ptrs[D]
ptrs[D] = (Arc *) ((uintptr_t) orig | 1);
}
// Sets marked pred/succ (to lower level) to the corresponding arc on proper level, unmarking it
template <Dir D>
void upgradeIfMarked() {
if ((uintptr_t) ptrs[D] & 1) {
ptrs[D] = (Arc *) ((uintptr_t) ptrs[D] & ~(uintptr_t)1);
ttassert(ptrs[D]->virtNode->virtParent);
ttassert(virtNode->node->boundary[D^arcIndex()] == ptrs[D]->virtNode->node->boundary[!D^ptrs[D]->arcIndex()]);
ttassert(
(virtNode->node->boundary[D^arcIndex()] == ptrs[D]->virtNode->virtParent->node->boundary[0]) ||
(virtNode->node->boundary[D^arcIndex()] == ptrs[D]->virtNode->virtParent->node->boundary[1]));
ptrs[D] = &ptrs[D]->virtNode->virtParent->arcs[
virtNode->node->boundary[D^arcIndex()] == ptrs[D]->virtNode->virtParent->node->boundary[D]];
ptrs[D]->ptrs[!D] = this;
ttassert(EIntegrity::template arcConsistency<D>(this));
}
}
// Determines whether eNode.boundary[i] is leaf where eNode.virtNode->arcs[!i] is this
bool isLeaf() {
return virtNode == succ()->virtNode;
}
bool canCompress() {
ttassert(!isLeaf());
return succ()->twin()->succ()->virtNode == virtNode;
}
bool canRake() {
ttassert(!isLeaf());
return succ()->isLeaf();
}
};
struct ENode;
struct VirtNode {
Arc arcs[2] = {this, this};
// inv: arcs[i] leads from node->boundary[i];
// inv: node was created through virt(node->children[0])->arc[...]->succ() pointer
ENode *node; // same as in child if dummy
VirtNode *virtParent = nullptr; // may refer to dummy, which is skipped by node->parent
Arc *childrenArcs[2] = {nullptr, nullptr}; // the arc through which node was created and its successor
private:
static inline VirtNode * const NOT_IN_LIST = (VirtNode * const) ~(uintptr_t)0;
VirtNode *listNode = NOT_IN_LIST;
public:
class List : private InnerList<VirtNode, &VirtNode::listNode> {
private:
using base = InnerList<VirtNode, &VirtNode::listNode>;
public:
using base::base;
using base::front;
using base::next;
using base::begin;
using base::end;
void append(VirtNode *node) {
ttassert(node != NOT_IN_LIST);
ttassert(node->listNode == NOT_IN_LIST);
node->listNode = NULL;
base::append(node);
}
bool tryAppend(VirtNode *node) {
ttassert(node != NOT_IN_LIST);
if (node->listNode != NOT_IN_LIST) {
return false;
}
append(node);
return true;
}
VirtNode *pop() {
VirtNode *node = base::pop();
ttassert(node != NOT_IN_LIST);
if (node) node->listNode = NOT_IN_LIST;
return node;
}
};
bool isDummy() {
return this != virt(node); // compares just pointers, should work even after deleting node
}
bool isMoveValid() {
ttassert(!isDummy());
return
childrenArcs[0] && (childrenArcs[0]->succ() == childrenArcs[1]) &&
(node->clusterType == COMPRESS ? childrenArcs[0]->canCompress() : childrenArcs[0]->canRake());
}
// Gets neighbouring arc on lower level incident to index'th arc as pred/succ
Arc *lowerLevelArcs(int index, typename Arc::Dir direction) {
ttassert(isDummy() || (node->clusterType != BASE));
Arc *arc = childrenArcs[0];
if (index == 0) {
if ((direction == Arc::Dir::SUCC) && !isDummy()) {
arc = arc->succ();
if (node->clusterType == RAKE) arc = arc->succ();
}
} else {
arc = arc->twin();
if ((direction == Arc::Dir::PRED) && !isDummy() && (node->clusterType == COMPRESS)) {
arc = arc->pred();
}
}
return arc->get(direction);
}
};
struct ENode : public Node {
VirtNode virtNode;
ENode() { virtNode.node = this; }
};
static ENode *ext(Node *node) { return static_cast<ENode *>(node); };
static VirtNode *virt(Node *node) { return &ext(node)->virtNode; };
InnerList<Node, &Node::tmpListNode> freeENodes;
ENode *newNode() {
ENode *node = this->template newNodeT<ENode>(freeENodes);
return node;
}
void deleteNode(Node *node) { this->template deleteNodeT<ENode>(node, freeENodes); }
InnerList<VirtNode, &VirtNode::virtParent> freeDummyNodes;
VirtNode *newDummyNode() {
if (freeDummyNodes.front()) {
return freeDummyNodes.pop();
}
return new VirtNode();
}
void deleteDummyNode(VirtNode *node) {
ttassert(!node->virtParent);
freeDummyNodes.push(node);
}
std::vector<Arc *> vertexToArc; // any arc leading from the vertex, or nullptr
VirtNode *tryJoin(Arc *arc);
void updateClusterization(typename VirtNode::List &&I, typename VirtNode::List &&D);
public:
virtual ~ContractionTopTree() {
this->rollback();
typename VirtNode::List D;
for (Arc *initArc : vertexToArc) {
if (!initArc || !D.tryAppend(initArc->virtNode)) continue;
for (Arc *arc = initArc->succ(); arc != initArc; arc = arc->succ()) {
D.tryAppend(arc->virtNode);
}
}
while (VirtNode *node = D.pop()) {
if (node->virtParent) D.tryAppend(node->virtParent);
if (node->isDummy()) {
delete node;
} else {
delete node->node; // node is part of node->node memory
}
}
while (ENode *node = ext(freeENodes.pop())) delete node;
while (VirtNode *node = freeDummyNodes.pop()) delete node;
}
};
template <class... TUserData>
void ContractionTopTree<TUserData...>::
link(Vertex u, Vertex v, TUserData... userData) {
this->rollback();
// XXX check whether possible
ENode *node = newNode();
node->setBoundary(u, v);
node->userData = {userData...};
if (vertexToArc.size() <= std::max(u, v)) {
vertexToArc.resize(std::max(u, v) + 1);
}
for (int i : {0, 1}) {
if (Arc *arc = vertexToArc[node->boundary[i]]) {
node->virtNode.arcs[!i].connectToTour(arc);
} else {
node->virtNode.arcs[!i].initLeaf();
vertexToArc[node->boundary[i]] = &node->virtNode.arcs[i];
}
}
typename VirtNode::List I;
I.append(&node->virtNode);
updateClusterization(std::move(I), {});
}
template <class... TUserData>
std::tuple<TUserData...> ContractionTopTree<TUserData...>::
cut(Vertex u, Vertex v) {
this->rollback();
ENode *node = ext(TopTree<TUserData...>::baseNode(u, v));
ttassert(node); // interface assert, maybe use exception instead
typename VirtNode::List D;
D.append(&node->virtNode);
for (int i : {0, 1}) {
if (node->virtNode.arcs[!i].isLeaf()) {
this->markVertexAsIsolated(node->boundary[i]);
ttassert(vertexToArc[node->boundary[i]] == &node->virtNode.arcs[i]);
vertexToArc[node->boundary[i]] = nullptr;
} else {
if (vertexToArc[node->boundary[i]] == &node->virtNode.arcs[i]) {
vertexToArc[node->boundary[i]] = node->virtNode.arcs[!i].succ();
}
node->virtNode.arcs[!i].disconnectFromTour();
}
}
if (node->parent) {
this->releaseNode(node->parent);
}
std::tuple<TUserData...> ret = std::move(node->userData);
updateClusterization({}, std::move(D));
return ret;
}
// Updates clusterization given inserted and deleted nodes on base level, see state below
template <class... TUserData>
void ContractionTopTree<TUserData...>::
updateClusterization(typename VirtNode::List &&I, typename VirtNode::List &&D) {
while (I.front() || D.front()) {
// state:
// level of nodes in I,D has complete Eulerian trail (incl. I, excl. D)
// I-nodes have no parents
// D-nodes have parents and should be destroyed, trail ptrs inconsistently points to original neighbours
typename VirtNode::List newI, newD, I2, N;
// lists:
// D nodes to be destroyed
// I newly inserted nodes without parents, need creating new parents, neighbours may have invalid parents
// I2 nodes disconnected from their invalidated parents, need creating new parents
// N neighbouring nodes with valid parents, but dummy parents may need replacement
// newI,newD lists of by one higher level
// Any node may be in at most one list at a time --
// trying to append the node to a second list has no effect;
// the order in which lists are created is thus very important.
// ADD siblings of D to I2, ADD parents to newD, DETACH from parents
for (VirtNode *node : D) {
VirtNode *parent = node->virtParent;
if (parent) {
if (parent->isDummy()) {
node->virtParent = nullptr;
parent->childrenArcs[0] = nullptr;
} else {
size_t i = parent->childrenArcs[0]->virtNode == node;
I2.tryAppend(node->virtParent->childrenArcs[i]->virtNode);
for (Arc *&arc : parent->childrenArcs) {
arc->virtNode->virtParent = nullptr;
arc = nullptr;
}
parent->node->detachChildren(); // needed if node isDummy and node->node still exists
}
newD.tryAppend(parent);
}
if (!node->isDummy() && node->node->parent) {
node->node->parent->detachChildren();
}
}
// TEST VALIDITY of parents of arc-neighbours of I, insert invalid to newD
// insert both children of invalid parent to I2, others to N
for (VirtNode *node2 : I) {
for (int i : {0, 1}) for (int d : {0, 1}) {
VirtNode *node = node2->arcs[i].get(d)->virtNode;
VirtNode *parent = node->virtParent;
if (parent && parent->isDummy()) {
N.tryAppend(node);
} else if (!parent) {
I2.tryAppend(node);
} else if (!parent->isMoveValid()) {
this->releaseNode(parent->node); // no effect if second child is already destroyed
for (Arc *&arc : parent->childrenArcs) {
I2.tryAppend(arc->virtNode);
arc->virtNode->virtParent = nullptr;
arc = nullptr;
}
if (node->node->parent) {
node->node->parent->detachChildren();
}
newD.tryAppend(parent);
}
}
}
// ADD neighbours of D and their neighbours to N
for (VirtNode *node : D) {
for (int i : {0, 1}) for (int d : {0, 1}) {
VirtNode *node2 = node->arcs[i].get(d)->virtNode;
N.tryAppend(node2);
for (int i : {0, 1}) for (int d : {0, 1}) {
N.tryAppend(node2->arcs[i].get(d)->virtNode);
}
}
}
// ADD neighbours of I2 to N
for (VirtNode *node : I2) {
for (int i : {0, 1}) for (int d : {0, 1}) {
N.tryAppend(node->arcs[i].get(d)->virtNode);
}
}
// DELETE nodes in D
while (VirtNode *node = D.pop()) {
if (node->isDummy()) {
deleteDummyNode(node);
} else {
deleteNode(node->node);
}
}
// CREATE new PARENTS of I,I2,N; insert them to newI
// temporary set their arc-ptrs to lower level nodes
// insert unneeded dummy nodes to newD
for (auto X : {&I, &I2, &N}) for (VirtNode *node : *X) {
for (int i : {0, 1}) {
VirtNode *newParent = tryJoin(&node->arcs[i]);
if (newParent) {
VirtNode *sibling = node->arcs[i].succ()->virtNode; // == newParent->childrenArcs[1]->virtNode
for (VirtNode *n : {node, sibling}) {
if (n->virtParent) {
ttassert(n->virtParent->isDummy());
n->virtParent->childrenArcs[0] = nullptr;
newD.append(n->virtParent);
}
n->virtParent = newParent;
}
newI.append(newParent);
ttassert(EIntegrity::childrenConsistency(newParent));
break;
}
}
}
while (N.pop());
// CREATE new DUMMY parents of nodes in I,I2 (unless neighbourless); insert them to newI
// copy even their arc-ptrs (temporary)
for (auto X : {&I, &I2}) while (VirtNode *node = (*X).pop()) {
ttassert(EIntegrity::childrenNeighbourhoodConsistency(node));
if (!node->node->parent) {
if (node->arcs[0].isLeaf() && node->arcs[1].isLeaf()) {
this->markNodeAsRoot(node->node);
if (node->virtParent) {
newD.append(node->virtParent);
node->virtParent->childrenArcs[0] = nullptr;
node->virtParent = nullptr;
}
ttassert(EIntegrity::treeConsistency(node->node));
} else if (!node->virtParent) {
VirtNode *newParent = newDummyNode();
newParent->childrenArcs[0] = &node->arcs[0];
node->virtParent = newParent;
newParent->node = node->node;
for (int i : {0, 1}) {
newParent->arcs[i].template setMarked<Arc::Dir::PRED>(node->arcs[i].pred());
newParent->arcs[i].template setMarked<Arc::Dir::SUCC>(node->arcs[i].succ());
}
newI.append(newParent);
ttassert(EIntegrity::childrenConsistency(newParent));
}
}
}
// DISCONNECT newD nodes from tour
for (VirtNode *node : newD) {
for (int i : {0, 1}) {
node->arcs[i].disconnectFromTour();
}
}
// UPGRADE ARC pointers in newI to higher level if needed
for (VirtNode *node : newI) {
for (Arc &arc : node->arcs) {
arc.template upgradeIfMarked<Arc::Dir::PRED>();
arc.template upgradeIfMarked<Arc::Dir::SUCC>();
}
ttassert(EIntegrity::nodeConsistency(node));
}
I = std::move(newI);
D = std::move(newD);
ttassert(!newI.front());
ttassert(!newD.front());
ttassert(!I2.front());
ttassert(!N.front());
}
}
template <class... TUserData>
typename ContractionTopTree<TUserData...>::VirtNode *ContractionTopTree<TUserData...>::
tryJoin(Arc *arc) {
if (
arc->isLeaf() ||
(arc->virtNode->virtParent && !arc->virtNode->virtParent->isDummy()) ||
(arc->succ()->virtNode->virtParent && !arc->succ()->virtNode->virtParent->isDummy())) {
return nullptr;
}
ClusterType clusterType;
if (arc->canCompress()) {
clusterType = COMPRESS;
} else if (arc->canRake()) {
clusterType = RAKE;
} else return nullptr;
for (Arc *arc : {arc, arc->succ()}) {
if (arc->virtNode->node->parent) {
ttassert(arc->virtNode->virtParent);
this->releaseNode(arc->virtNode->node->parent);
arc->virtNode->node->detach();
}
}
ENode *node = newNode();
node->attachChildren(clusterType, arc->virtNode->node, arc->succ()->virtNode->node);
this->vertexToNodeUpdateInner(node);
node->virtNode.childrenArcs[0] = arc;
node->virtNode.childrenArcs[1] = arc->succ();
VirtNode *virtNode = &node->virtNode;
for (int i : {0, 1}) {
virtNode->arcs[i].template setMarked<Arc::Dir::PRED>(virtNode->lowerLevelArcs(i, Arc::Dir::PRED));
virtNode->arcs[i].template setMarked<Arc::Dir::SUCC>(virtNode->lowerLevelArcs(i, Arc::Dir::SUCC));
}
ttassert(virtNode->node == node);
return virtNode;
}
}
using TopTreeInternals::ContractionTopTree;
#undef ttassert
#endif