Olympiad in Informatics

Virtual Tree

Overview

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

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:

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]);
}