-
Notifications
You must be signed in to change notification settings - Fork 108
/
Tree Construction with Specific Vertices.cpp
69 lines (68 loc) · 1.24 KB
/
Tree Construction with Specific Vertices.cpp
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
69
/* This code builds an auxiliary tree from the given vertices to do
further operations. Example problem: CF 613D */
void dfs(int u, int p=0, int d=0)
{
tin[u]=++t;
parent[u][0]=p;
level[u]=d;
for(auto v: graph[u])
{
if(v==p) continue;
dfs(v,u,d+1);
}
tout[u]=t;
}
void cleanup(vi &vtx)
{
for(auto it: vtx)
{
tree[it].clear();
}
}
bool isancestor(int u, int v) // Check if u is an ancestor of v
{
return (tin[u]<=tin[v]) && (tout[v]<=tout[u]);
}
// building the auxiliary tree. Nodes are in vtx
void sortbyEntry(vi &vtx)
{
// Sort by entry time
sort(begin(vtx), end(vtx), [](int x, int y){
return tin[x]<tin[y];
});
}
void release(vi &vtx)
{
// removing duplicated nodes
SORT(vtx);
vtx.erase(unique(begin(vtx),end(vtx)),end(vtx));
}
void buildTree(vi &vtx)
{
stack<int> st;
st.push(vtx[0]);
FOR(i,1,vtx.size())
{
while(!isancestor(st.top(),vtx[i]))
st.pop();
tree[st.top()].pb(vtx[i]);
st.push(vtx[i]);
}
}
int work(vi &vtx)
{
sortbyEntry(vtx);
int sz=vtx.size();
// Finding all the ancestors, there are few of them
FOR(i,0,sz-1)
{
int anc=query(vtx[i],vtx[i+1]);
vtx.pb(anc);
}
release(vtx);
sortbyEntry(vtx);
buildTree(vtx);
// Do necessary operation on the built auxiliary tree
cleanup(vtx);
// return result
}