---
id: 2657
lang: en
translation_of: index.md
source_sha256: 5e1b32c238e80714a95a6c0f03ec37d85f10a3ba333feba3e0c29128b184933b
title: "Virtual Tree"
description: "A flexible data structure for computing on a set of key vertices of a tree, plus how to build it with a stack."
tags: ["OI","Virtual Tree","Data Structures"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "The Construction paragraph ends with a parenthetical and no final period in the Chinese; kept that way."
---

## Overview

A flexible data structure for performing computations on a set of key vertices in a tree.

<!--more-->

## Construction

First, shove node $1$ into the stack. Then, from the point set sorted by $DFS$ order, take the current smallest point and call it $x$, and take its $LCA$ with the top of the stack as $d$. If this $d$ is the top of the stack, it can be put straight onto the stack; otherwise it means they are not on one chain, and we need to pop the stack until the current point $x$ can be on one chain. To do this, we need to compare the second node of the stack with $d$ (there is the case where the top of the stack is $d$, and in that case we need to modify the stack top directly)

Roughly, you write it like this:

```cpp
void build_virtual_tree()
{
    // ktot;
    // kseq;
    sort(kseq + 1, kseq + 1 + ktot, [](const int &rhs1, const int &rhs2) { return dfn[rhs1] < dfn[rhs2]; });
    stk[++tail] = 1;
    for (int i = 1; i <= ktot; i++)
    {
        int x = kseq[i], d = getLCA(x, stk[tail]);
        if (x != 1)
        {
            while (dfn[stk[tail - 1]] > dfn[d])
                G[stk[tail - 1]].push_back(stk[tail]), tail--;
            if (dfn[stk[tail - 1]] < d)
                G[d].push_back(stk[tail]), stk[tail] = d;
            else
                G[d].push_back(stk[tail]), tail--;
        }
        stk[++tail] = x;
    }
    for (int i = 1; i < ktot; i++)
        G[stk[i]].push_back(stk[i + 1]);
}
```
