Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <queue>
- #include <vector>
- #include <fstream>
- #include <cstring>
- using namespace std;
- const int maxn = 2e5 + 10;
- const int logn = 24;
- int n;
- vector<int> graph[maxn];
- int timer = 0;
- int in_dfs[maxn], out_dfs[maxn];
- int parent[maxn];
- int up_node[maxn][logn];
- void dfs(int node, int parent) {
- timer++;
- in_dfs[node] = timer;
- up_node[node][0] = parent;
- for(int i = 1; i < logn; i++) {
- up_node[node][i] = up_node[up_node[node][i - 1]][i - 1];
- }
- for(int neighbour : graph[node]) {
- if(neighbour != parent) {
- dfs(neighbour, node);
- }
- }
- timer++;
- out_dfs[node] = timer;
- }
- bool is_ancestor(int A, int B) {
- if(in_dfs[A] <= in_dfs[B] and out_dfs[A] >= out_dfs[B]) {
- return true;
- }
- return false;
- }
- int LCA(int A, int B) {
- if(is_ancestor(A, B)) {
- return A;
- }
- if(is_ancestor(B, A)) {
- return B;
- }
- for(int i = logn - 1; i >= 0; i--) {
- if(!is_ancestor(up_node[A][i], B)) {
- A = up_node[A][i];
- }
- }
- // cout << A << endl;
- return up_node[A][0];
- }
- int main() {
- int q;
- cin >> n >> q;
- parent[1] = 0;
- for(int i = 2; i <= n; i++) {
- int p;
- cin >> p;
- graph[i].push_back(p);
- graph[p].push_back(i);
- parent[i] = p;
- }
- dfs(1, 1);
- for(int i = 0; i < q; i++) {
- int a, b;
- cin >> a >> b;
- cout << LCA(a, b) << endl;
- }
- return 0;
- }
- /*
- 12
- 1 2
- 2 4
- 2 5
- 4 7
- 5 8
- 1 3
- 3 6
- 6 9
- 6 10
- 6 11
- 11 12
- **/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement