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 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 vertices when .
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 , pop until the top is an ancestor of . If the stack is nonempty, connect its top to , then push .
This works because LCAs have already been added. The nearest retained ancestor is present before 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 verticessort vertices by DFS entry time; remove duplicatesstack = emptyfor 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 is distance_from_root[v] - distance_from_root[u], not one.
Count pairs by cuts
Let be the number of selected vertices in the virtual subtree of child . Removing edge separates selected vertices from others. Exactly unordered pairs use that edge. Its contribution is
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.
worked query
Take edges of length two, of length three, of length five, and of length seven. Select . The closure is ; vertex four disappears, and compressed edge has length twelve.
Edge separates two selected vertices from one, contributing four. Edge contributes six. Edge contributes 24. The sum is 34, agreeing with direct distances , , and .
Complexity and engineering details
With binary-lifting LCA, a query costs , and the virtual DP is linear in the closure size. Preprocessing costs . Across many queries, the useful bound is expressed using the total number of selected vertices, not times the number of queries.
Clear only vertices touched by the current query, or allocate query-local adjacency. Resetting an -element array per query would undo the improvement. Deduplicate selections for set semantics; if repeated selections represent multiplicities, preserve counts and replace 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 . 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!




























































Conversation
Comments powered by Waline