Skip to content

Commit

Permalink
Merge pull request #4347 from danielzsh/patch8
Browse files Browse the repository at this point in the history
  • Loading branch information
danielzsh authored Feb 27, 2024
2 parents 7dca467 + 1ba42af commit f35bbb1
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions content/5_Plat/Centroid.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,6 @@ or equal to $\frac{N}{2}$, then it is a centroid. Otherwise, move to the child
with a subtree size that is more than $\frac{N}{2}$ and repeat until you find a
centroid.





### Implementation

<LanguageSection>
Expand Down Expand Up @@ -198,6 +194,28 @@ subgraphs.
The implementation by
[Carpanese](https://medium.com/carpanese/an-illustrated-introduction-to-centroid-decomposition-8c1989d53308#d10f)
(ll. 20-21) leads to a segmentation fault due to an invalidated iterator in the range-based for loop after erasing the element.
Instead, you can store an `is_removed` array and check it before visiting children (this approach is presented below).
Alternatively, the following code in the Carpanese article (line 3 is the problematic one):
```cpp
for (auto v : tree[centroid])
tree[centroid].erase(v), // remove the edge to disconnect
tree[v].erase(centroid), // the component from the tree
build(v, centroid);
```

Can be rewritten like so:

```cpp
for (auto v : tree[centroid]) {
tree[v].erase(centroid);
build(v, centroid);
}
tree[centroid].clear();
```

The article also mentions an update complexity of $\mathcal{O}(\log^2n)$ because it assumes an additional factor of $\mathcal{O}(\log n)$ to calculate the distance between a node and a given centroid ancestor.
However, we can precompute these (as demonstrated in the code below) to reduce update complexity to $\mathcal{O}(\log n)$ and overall complexity to $\mathcal{O}((N + Q)\log n)$.

</Warning>

Expand Down

0 comments on commit f35bbb1

Please sign in to comment.