Cod sursa(job #2398422)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 5 aprilie 2019 14:41:26
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb

#include <bits/stdc++.h>
#define zeros(x)  (x & (-x))
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
const int MAXN =  15 + 1e5;
int father[35][MAXN], dist[MAXN];
vector <int> g[MAXN];
void dfs(int node, int papa){
    dist[node] = dist[papa] + 1;
    for(auto y : g[node]){
        if(y  != papa){
            dfs(y, node);
        }
    }
}
int fth(int u, int v){
    for(int i = 29; i >= 0 ; -- i){
        if(father[i][u] != father[i][v]){
            u = father[i][u];
            v = father[i][v];
        }
    }
    return father[0][u];
}
int schimbare(int x, int node){
    for(int i = 0; (1 << i) <= x; ++i)
        if(x & (1 << i)) node = father[i][node];
    return node;
}
int query(int st, int dr){
    if(dist[st] < dist[dr]) swap(st, dr);
    int dif = dist[st] - dist[dr] ;
    st = schimbare(dif, st);
    if(st == dr) return st;
    return fth(st, dr);
}

int main(){
    int n, m;
    fin >> n >> m;
    for(int i = 2; i <= n; ++i){
        int x;
        fin >> x;
        father[0][i] = x;
        g[x].push_back(i);
    }
    dist[0] = -1;
    dfs(1, 0);
    for(int node = 1; node <= n; ++node){
        for(int i = 1; i <= 29; ++i){
            father[i][node] = father[i - 1][father[i - 1][node]];
        }
    }
    for(int i = 1; i <= m; ++i){
        int p, q;
        fin >> p >> q;
        fout << query(p, q) << '\n';
    }
    return 0;

}