Skip to content

heavyLightDecomposition ​

heavyLightDecomposition(adj: usize[][], root: usize): Hld builds a heavy-light decomposition over the undirected tree described by the adjacency list adj, where adj[v] holds the neighbors of vertex v and root anchors every query. The returned Hld is an owned handle of tyrus:algorithm; it exposes queryPath(u, v), which returns the contiguous [l, r] ranges (in position order) whose union covers the tree path u → v in O(log n), ready to feed a segment tree for path queries.

Construction ​

SyntaxDescription
heavyLightDecomposition(adj: usize[][], root: usize)Decompose the tree adj into heavy chains, rooted at root

Methods ​

MethodSignatureReturnsDescription
queryPath(u: usize, v: usize)[usize, usize][]Chain ranges whose union covers the tree path u → v
position(v: usize)usizeChain-linear position of vertex v
head(v: usize)usizeTopmost vertex of the heavy chain containing v

Complexity ​

OperationTime Complexity
constructionO(n), one DFS plus chain assignment
queryPathO(log n), at most O(log n) chain ranges
position, headO(1)
memoryO(n)

Examples ​

balanced tree ​

tyrus
import { heavyLightDecomposition } from "tyrus:algorithm";

const adj: usize[][] = [[1, 2], [0, 3, 4], [0, 5, 6], [1], [1], [2], [2]];
const hld = heavyLightDecomposition(adj, 0);

print(hld.queryPath(3, 4));  // [[3, 3], [1, 2]]
print(hld.queryPath(5, 4));  // [[4, 5], [3, 3], [0, 1]]
print(hld.position(3));  // 2
print(hld.head(3));  // 0

deep path ​

tyrus
import { heavyLightDecomposition } from "tyrus:algorithm";

const path: usize[][] = [[1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8]];
const hld = heavyLightDecomposition(path, 0);

print(hld.queryPath(9, 1));  // [[1, 9]]
print(hld.queryPath(0, 9));  // [[0, 9]]

single vertex ​

tyrus
import { heavyLightDecomposition } from "tyrus:algorithm";

const single: usize[][] = [[]];
const hld = heavyLightDecomposition(single, 0);

print(hld.queryPath(0, 0));  // [[0, 0]]

namespace import ​

tyrus
import * as alg from "tyrus:algorithm";

const hld = alg.heavyLightDecomposition([[1], [0, 2], [1]], 0);
print(hld.queryPath(1, 2));  // [[1, 2]]