-
Notifications
You must be signed in to change notification settings - Fork 0
/
auxiliarytree.hpp
68 lines (66 loc) · 1.7 KB
/
auxiliarytree.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#pragma once
#include "Graph/lca.hpp"
struct AuxiliaryTree{
int n,pos;
LCA lca;
vector<int> in,dep;
vector<vector<int>> _g,g;
AuxiliaryTree(int _n):n(_n),pos(0),lca(n),in(n),dep(n),_g(n),g(n){}
void add_edge(int u,int v){
lca.add_edge(u,v);
_g[u].push_back(v);
_g[v].push_back(u);
}
void run(int root=0){
lca.run(root);
dfs(root,-1);
}
void query(vector<int>& vs){
sort(ALL(vs),[&](int u,int v){return in[u]<in[v];});
vs.erase(unique(ALL(vs)),vs.end());
int m=vs.size();
stack<int> st;
st.push(vs[0]);
rep(i,0,m-1){
int w=lca.lca(vs[i],vs[i+1]);
if(w!=vs[i]){
int cur=st.top();
st.pop();
while(!st.empty() and dep[w]<dep[st.top()]){
add(st.top(),cur);
cur=st.top();
st.pop();
}
if(st.empty() or st.top()!=w){
st.push(w);
vs.push_back(w);
}
add(w,cur);
}
st.push(vs[i+1]);
}
while(st.size()>1){
int c=st.top();
st.pop();
add(st.top(),c);
}
}
void clear(vector<int>& vs){
for(auto& w:vs)g[w].clear();
}
private:
void dfs(int v,int p){
in[v]=pos++;
for(auto& to:_g[v])if(to!=p){
dep[to]=dep[v]+1;
dfs(to,v);
}
}
void add(int u,int v){
g[u].push_back(v);
g[v].push_back(u);
}
};
/**
* @brief Auxiliary Tree(Virtual Tree)
*/