Persistent meldable heap

Persistent meldable heaps are generally used to solve the kk-shortest paths problem.

If a meldable heap has non-amortized time complexity, then after persistence the time complexity of each operation is guaranteed to be O(log⁡n)O(\log n); in other words, special data cannot cause the complexity to deteriorate.

Persistent leftist tree

Before studying this topic, first learn about leftist trees.

Procedure

Recall the merging process for leftist trees. Suppose we want to merge two leftist trees with respective roots x,yx,y, and both maintained leftist trees satisfy the min-heap property:

  1. If one of the nodes x,yx,y is empty, return x+yx+y.

  2. Choose the node with the smaller value among x,yx,y as the root of the merged leftist tree.

  3. Recursively merge the right subtree of xx with yy, and make the root of the merged tree the right child of xx.

  4. Restore the leftist property of the current merged tree, maintain its dist value, and return the selected root.

Because each recursive call decreases dist[x]+dist[y] by one, while dist[x] is O(log⁡n)O(\log n), at most O(log⁡n)O(\log n) nodes are modified in one operation. Thus the time complexity is O(log⁡n)O(\log n).

Persistence requires retaining historical information so that earlier versions can be accessed later. To make a leftist tree persistent, copy the path modified along the way.

Therefore, the merging process for a persistent leftist tree is as follows:

  1. If one of the nodes x,yx,y is empty, return x+yx+y.

  2. Choose the node with the smaller value among x,yx,y, create a copy pp of that node, and use it as the root of the merged persistent leftist tree.

  3. Recursively merge the right subtree of pp with yy, and make the root of the merged tree the right child of pp.

  4. Restore the leftist property of the tree rooted at pp, maintain its dist value, and return pp.

Because a leftist tree modifies and creates at most O(log⁡n)O(\log n) nodes per operation, if the number of operations is mm, both the time and space complexity of a persistent leftist tree are O(mlog⁡n)O(m\log n).

Reference implementation

int merge(int x, int y) {
  if (!x || !y) return x + y;
  if (v[x] > v[y]) swap(x, y);
  int p = ++cnt;
  lc[p] = lc[x];
  v[p] = v[x];
  rc[p] = merge(rc[x], y);
  if (dist[lc[p]] < dist[rc[p]]) swap(lc[p], rc[p]);
  dist[p] = dist[rc[p]] + 1;
  return p;
}

This content comes from OI Wiki: Persistent meldable heap. See the original for authors and revision history. AIOJ has adapted the formatting, in-site links, and resource paths.

Content is shared under CC BY-SA 4.0 and SATA license; additional terms are governed by the original notice. Thanks to the OI Wiki authors and contributors; per the SATA terms, please visit the OI Wiki repository and star it to show your support.