Video failed to load

Virtual Trees: Compress a Huge Tree Around a Small Query

641 words
3 minutes
Virtual Trees: Compress a Huge Tree Around a Small Query
Virtual Trees: Compress a Huge Tree Around a Small Query

A tree may have hundreds of thousands of vertices while each query mentions only a handful. Running a whole-tree DP for every query wastes almost all its work. A virtual tree keeps selected vertices and the branching points that matter, replacing long uninteresting paths with annotated edges.

Assume the original tree is rooted and preprocessed for entry times, ancestor tests, lowest common ancestors, and weighted root distances. We will solve the following query task: sum distances over all unordered pairs of selected vertices.

Find the necessary branching points#

Sort the kk selected vertices by DFS entry time. Add the LCA of each consecutive pair in this order, then sort and deduplicate again. The resulting LCA closure has at most 2k−12k-1 vertices when k>0k>0.

Why do consecutive pairs suffice? Each retained branching point separates at least two occupied child subtrees. The selected vertices in each such subtree occupy a contiguous DFS interval. At a boundary between two occupied intervals, two consecutive selected vertices have that branching point as their LCA.

Nodes that are merely degree-two waypoints along these connecting paths are unnecessary. Their effect can be stored on a compressed edge.

Build edges with an ancestor stack#

The closure is now sorted in DFS order. Maintain a stack of ancestors. For each vertex vv, pop until the top is an ancestor of vv. If the stack is nonempty, connect its top to vv, then push vv.

This works because LCAs have already been added. The nearest retained ancestor is present before vv and remains on the stack. Without the closure step, popping could skip the required branching vertex and silently create the wrong tree.

vertices = selected vertices plus LCAs of adjacent selected vertices
sort vertices by DFS entry time; remove duplicates
stack = empty
for v in vertices:
while stack is not empty and not ancestor(stack.back, v):
stack.pop_back()
if stack is not empty:
add compressed edge stack.back -> v
stack.push_back(v)

The length of a compressed ancestor edge (u,v)(u,v) is distance_from_root[v] - distance_from_root[u], not one.

Count pairs by cuts#

Let svs_v be the number of selected vertices in the virtual subtree of child vv. Removing edge (u,v)(u,v) separates svs_v selected vertices from k−svk-s_v others. Exactly sv(k−sv)s_v(k-s_v) unordered pairs use that edge. Its contribution is

length⁡(u,v) sv(k−sv).\operatorname{length}(u,v)\,s_v(k-s_v).

Sum these values over virtual edges. Every original edge compressed into the same virtual edge has the same selected-vertex partition, so replacing the path by its total length preserves the answer exactly.

compressed length w

Retained branching vertex u

Retained descendant v

s selected vertices below

k minus s selected vertices outside

compressed length w

Retained branching vertex u

Retained descendant v

s selected vertices below

k minus s selected vertices outside

worked query#

Take edges (1,2)(1,2) of length two, (2,3)(2,3) of length three, (2,4)(2,4) of length five, and (4,5)(4,5) of length seven. Select {1,3,5}\{1,3,5\}. The closure is {1,2,3,5}\{1,2,3,5\}; vertex four disappears, and compressed edge (2,5)(2,5) has length twelve.

Edge (1,2)(1,2) separates two selected vertices from one, contributing four. Edge (2,3)(2,3) contributes six. Edge (2,5)(2,5) contributes 24. The sum is 34, agreeing with direct distances d(1,3)=5d(1,3)=5, d(1,5)=14d(1,5)=14, and d(3,5)=15d(3,5)=15.

Complexity and engineering details#

With binary-lifting LCA, a query costs O(klog⁡k+klog⁡n)O(k\log k+k\log n), and the virtual DP is linear in the closure size. Preprocessing costs O(nlog⁡n)O(n\log n). Across many queries, the useful bound is expressed using the total number of selected vertices, not nn times the number of queries.

Clear only vertices touched by the current query, or allocate query-local adjacency. Resetting an nn-element array per query would undo the improvement. Deduplicate selections for set semantics; if repeated selections represent multiplicities, preserve counts and replace kk by total multiplicity in the contribution formula.

For path-minimum cut problems, annotate compressed edges with their path minimum instead of their length. The virtual topology is reusable, but the annotation must match the operation being preserved.

Exercise. Give each selected vertex a positive weight. Derive the weighted sum of pair distances and explain why the edge contribution becomes weSv(S−Sv)w_e S_v(S-S_v). Test a selected ancestor and selected descendant together, since selected vertices are not necessarily leaves of the virtual tree.

Support & Share

If this article helped you, please share or support!

Sponsor
Virtual Trees: Compress a Huge Tree Around a Small Query
https://blog.wsh.moe/posts/virtual-tree-pair-distances/
Author
Wsh
Published at
2026-10-24

Comments

LEAVE A NOTE

Join the conversation

Markdown supported

Be kind. Good conversations start with you.

Conversation

Loading conversation…

Comments powered by Waline

Profile Image of the Author
Wsh
Nice to meet you! Hello, I'm Wsh.
Announcement
Any news or updates will be shared here, so check back anytime! Thanks for stopping by, meow >.<
Categories
Tags
Site Statistics
Posts
27
Categories
7
Tags
69
Total Words
124,615
Running Days
0 days
Last Activity
0 days ago
Site Info
Build Platform
Vercel
Blog Version
Firefly v6.16.8
License
CC BY-NC-SA 4.0
Table of Contents