-
Notifications
You must be signed in to change notification settings - Fork 4
/
Long-paths:<O(n,sqrt(n))>.cpp
85 lines (74 loc) · 2.27 KB
/
Long-paths:<O(n,sqrt(n))>.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// github.com/andy489
#include <iostream>
#include <vector>
#include <list>
using namespace std;
#define ios ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
#define pb push_back
int n, leaves;
vector<list<int>> adj{{},{2,3},{1,4,5,6},{1},{2},{2,7,8},{2},{5,9},{5,14},{7,11},{14},{9,12},{11},{14},{8,10,13}}, AL;
vector<int> par, dep, SL, mark, indexp; // parent func., depth dunc., Sorted Leaves, visited, index path
vector<vector<int>> P; // max-Paths
void init() { // hardcoded Tree
n = (int)adj.size();
par.resize(n), dep.resize(n, -1);
AL.resize(n), mark.resize(n), indexp.resize(n);
}
void dfs(int u = 1, int p = 0) {
par[u] = p; // parent function fill
dep[u] = dep[p] + 1; // depth function fill
if (adj[u].size() == 1) AL[dep[u]].push_back(u), ++leaves; /// All Leaves array of lists
for (const int &child:adj[u]) {
if (child == p) continue;
dfs(child, u);
}
}
void counting() {
SL.resize(leaves); // Sorted Leaves (decreasing)
int k = 0;
for (int d = n - 1; d >= 0; --d) {
while (!AL[d].empty()) {
auto it = --AL[d].end();
int l = *it;
AL[d].erase(it), SL[k++] = l;
}
}
}
void maxPathsDecomposition() {
for (int l = 0; l <= leaves - 1; ++l) {
vector<int> currMaxPath;
int v = SL[l];
while (v && !mark[v]) {
currMaxPath.pb(v);
indexp[v] = l;
mark[v] = true;
v = par[v];
}
P.pb(currMaxPath); // P = Max Paths Decomposition
}
}
int LAQ2(int v, int d) {
if (d > dep[v]) return -1;
int u = P[indexp[v]].back(); // top element in curr max path
int dprim = dep[v] - dep[u];
if (d <= dprim) {
int depFirst = dep[P[indexp[v]][0]];
int depStart = depFirst - dep[v];
return P[indexp[v]][depStart + d];
}
return LAQ2(par[u], d - dprim - 1);
}
void solve() {
int q, v, d; cout << "Enter number of queries of the form \"v d\": ";
cin >> q;
cout<<"Enter query \"v d\":\n";
while (q--) {
cin >> v >> d;
int ans = LAQ2(v, d); // O(sqrt(n))
ans == -1 ? cout << "no such ancestor\n" : cout << ans<<'\n';
}
}
int main() {
ios;
return init(), dfs(), counting(), maxPathsDecomposition(), solve(), 0;
}