File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Kth Ancestor of a treenode using Binary Lifting. If kth ancestor does not exist, return -1. Implemented in C++17
2
+ // author : github.com/yadavnaman
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ class TreeAncestor {
7
+
8
+ public:
9
+ vector< vector<int > >dp; // dp[i][node] : node's 2^i parent
10
+ int n;
11
+ TreeAncestor (int m, vector<int >& parent) {
12
+ n = m;
13
+ dp.resize (20 ,vector<int > (m,-1 ));
14
+ for (int node = 0 ; node < parent.size (); ++node){
15
+ dp[0 ][node] = parent[node];
16
+ }
17
+ // 2^i parent
18
+ for (int i = 1 ; i< 20 ; ++i) {
19
+ for (int node = 0 ; node < parent.size (); ++node) {
20
+ int node_par = dp[i-1 ][node];
21
+ if (node_par != -1 ){
22
+ dp[i][node] = dp[i-1 ][node_par];
23
+ }
24
+ }
25
+ }
26
+
27
+ }
28
+
29
+ int getKthAncestor (int node, int k) {
30
+ for (int i = 0 ; i < 20 ; ++i) {
31
+ if (k & (1 <<i)) {
32
+ node = dp[i][node];
33
+ if (node == -1 ){
34
+ return -1 ;
35
+ }
36
+ }
37
+ }
38
+ return node;
39
+ }
40
+ };
41
+
42
+ int main () {
43
+ int m,k,node;
44
+ cin >> m >> k;
45
+ vector<int > par (m);
46
+ for (int i = 0 ; i < m; ++i){
47
+ cin>>par[i];
48
+ }
49
+ cin >> node;
50
+ TreeAncestor* obj = new TreeAncestor (m,par);
51
+ cout << obj->getKthAncestor (node,k) <<" \n " ;
52
+ }
You can’t perform that action at this time.
0 commit comments