41 lines
1.1 KiB
C++
41 lines
1.1 KiB
C++
/*
|
|
Search for the Kth Ancestor of a Tree Node
|
|
*/
|
|
#include <vector>
|
|
#include <bit>
|
|
#include <bitset>
|
|
#include <cstdint>
|
|
|
|
class TreeAncestor {
|
|
private:
|
|
std::vector<std::vector<int>> predecessor;
|
|
|
|
public:
|
|
TreeAncestor(int n, std::vector<int>& parent) {
|
|
int m = bit_width((unsigned)n);
|
|
predecessor.resize(n, std::vector<int>(m, -1));
|
|
for (int i = 0; i < n; i++) {
|
|
predecessor[i][0] = parent[i];
|
|
}
|
|
for (int i = 1; i < m; i++) {
|
|
for (int x = 0; x < n; x++) {
|
|
if (int p = predecessor[x][i - 1]; p != -1) {
|
|
predecessor[x][i] = predecessor[p][i - 1];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
int getKthAncestor(int node, int k) {
|
|
// for (int i = 0; i < bit_width((unsigned)k) && node != -1; i++) {
|
|
// if (k >> i & 1) {
|
|
// node = predecessor[node][i];
|
|
// }
|
|
// }
|
|
for (; k && node != -1; k &= k - 1) {
|
|
node = predecessor[node][countr_zero(unsigned(k))];
|
|
}
|
|
return node;
|
|
}
|
|
};
|