Dsu with lazy propagation

Правка en2, от pcheloveks, 2025-11-09 23:27:42

A trick for DSU (disjoint set union) that I recently came across:

We have elements on which we need to perform two types of queries:

  1. Union — merge the sets containing elements v1 and v2.
  2. Add — for all i in the set containing element v, add some value x to a[i].

To support this efficiently, we can store implicit modifications in the nodes, similar to lazy propagation in a segment tree, but without explicitly pushing updates down.

For an add query, we find the root of the tree containing vertex v and add the modification to that root. When we need to get the actual value of a[i], we first compress the path to the root and apply the root’s modification. During path compression (in the recursive process of reattaching the nodes), we also apply the parent’s modification to the current node.

For the union operation, we can either:

  1. create a new virtual node to act as the parent of both components.
  2. attach one root under the other and apply the inverse modification to the subtree that now becomes a child.

The second approach is a bit trickier to implement when the modifications are more complex.

code:

Spoiler

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
ru4 Русский pcheloveks 2025-11-09 23:58:14 1774 (опубликовано)
en2 Английский pcheloveks 2025-11-09 23:27:42 0 (published)
en1 Английский pcheloveks 2025-11-09 23:24:52 1928 Initial revision for English translation (saved to drafts)
ru3 Русский pcheloveks 2025-11-09 23:17:35 40
ru2 Русский pcheloveks 2025-11-09 23:16:17 4
ru1 Русский pcheloveks 2025-11-09 23:10:50 1883 Первая редакция (сохранено в черновиках)