// needs dfs in- and out- time and lca function vector in, out; void virtualTree(const vector& a) { // takes indices of used nodes auto ind = a; sort(all(ind), [&](int x, int y) {return in[x] < in[y];}); for (int i=0; i> tree(n); stack st{{0}}; for (int i=1; i= out[ind[st.top()]]) st.pop(); tree[st.top()].push_back(i); st.push(i); } // virtual directed tree with n nodes, original indices in ind // weights can be calculated if necessary, e.g. with binary lifting }