Skip to content

Commit afebfa6

Browse files
authored
Merge pull request #137 from Aakanksha2518/main
added solution for company queries 1
2 parents 8f8def2 + 2adf4c9 commit afebfa6

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <cmath>
4+
#include <algorithm>
5+
6+
using namespace std;
7+
8+
int n, q;
9+
int max_log;
10+
vector<vector<int>> up;
11+
vector<int> depth;
12+
13+
void dfs(int u, int p, int d, const vector<vector<int>>& child_list_ref) {
14+
depth[u] = d;
15+
up[u][0] = p;
16+
17+
for (int j = 1; j <= max_log; ++j) {
18+
up[u][j] = up[up[u][j - 1]][j - 1];
19+
}
20+
21+
for (int v : child_list_ref[u]) {
22+
dfs(v, u, d + 1, child_list_ref);
23+
}
24+
}
25+
26+
int get_kth_ancestor(int u, int k) {
27+
if (k > depth[u]) {
28+
return -1;
29+
}
30+
31+
for (int j = max_log; j >= 0; --j) {
32+
if (k & (1 << j)) {
33+
u = up[u][j];
34+
}
35+
}
36+
return u;
37+
}
38+
39+
int main() {
40+
ios_base::sync_with_stdio(false);
41+
cin.tie(NULL);
42+
43+
if (!(cin >> n >> q)) return 0;
44+
45+
max_log = log2(n) + 1;
46+
47+
up.assign(n + 1, vector<int>(max_log + 1, 0));
48+
depth.assign(n + 1, 0);
49+
50+
vector<vector<int>> child_list(n + 1);
51+
52+
for (int i = 2; i <= n; ++i) {
53+
int boss;
54+
if (!(cin >> boss)) return 0;
55+
child_list[boss].push_back(i);
56+
}
57+
58+
up[1][0] = 0;
59+
60+
dfs(1, 0, 0, child_list);
61+
62+
for (int i = 0; i < q; ++i) {
63+
int x, k;
64+
if (!(cin >> x >> k)) return 0;
65+
cout << get_kth_ancestor(x, k) << "\n";
66+
}
67+
68+
return 0;
69+
}

0 commit comments

Comments
 (0)