Cod sursa(job #2395129)

Utilizator Bulboaca_EugenBulboaca Alexandru Eugen Bulboaca_Eugen Data 2 aprilie 2019 11:40:23
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>
#define zeros(x)  (x & (-x))
using namespace std;
const int MAXN =  15 + 1e5;
int father[35][MAXN];
int fth(int u, int v){
    int linie = 0;
    for(int i = 29; i >= 0 ; -- i){
        if(father[i][u] != father[i][v]){
            u = father[i][u];
            v = father[i][v];
            linie = i;
        }
    }
    return father[linie][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;
}
bool schimbare1(int x, int node){
    for(int i = 0; (1 << i) <= x; ++i)
        if(x & (1 << i)) node = father[i][node];
    if(node >= 1) return true;
    return false;
}
int adancime(int node){
    int current = 0;
    for(int power = 24; power >= 0; --power){
        if(schimbare1(current + (1 << power), node)) current += (1 << power);
    }
    return current;
}
ifstream fin("lca.in");
ofstream fout("lca.out");
int main(){
    int n, m;
    fin >> n >> m;
    for(int i = 2; i <= n; ++i){
        int x;
        fin >> x;
        father[0][i] = x;
    }
    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, d1, d2, dif;
        fin >> q >> p;
        if(adancime(p) > adancime(q)) swap(p , q);
        d1 = adancime(p);
        d2 = adancime(q);
        dif = d2 - d1;
        q = schimbare(dif, q);
        if(p == q) fout << q << '\n';
        else fout << fth(p , q) << '\n';
    }
    return 0;
}