Cod sursa(job #2441621)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 20 iulie 2019 18:17:18
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int n, l = 200;
int anc[MAXN];
int radanc[MAXN], niv[MAXN];
vector<int> graf[MAXN];
int dp[MAXN][30];

void batog(int nod, int tata, int nivel){
    radanc[nod] = tata;
    niv[nod] = nivel;
    if(nivel % l == 0) tata = nod;
    for(auto x:graf[nod])
        batog(x, tata, nivel + 1);
}

void prec(){
    batog(1, 0, 0);
    for(int i = 1; i <= n; ++i) dp[i][0] = anc[i];
    for(int i = 1; i <= n; ++i){
        for(int j = 1; j <= 20; ++j)
            dp[i][j] = dp[dp[i][j - 1]][j - 1];
    }
}

int solve1(int x, int y){
    while(x != y){
        if(x > y) x = anc[x];
        else y = anc[y];
    }
    return x;
}
int solve2(int x, int y){
    while(radanc[x] != radanc[y]){
        if(niv[x] > niv[y]) x = radanc[x];
        else y = radanc[y];
    }
    while(x != y){
        if(niv[x] > niv[y]) x = anc[x];
        else y = anc[y];
    }
    return x;
}
int solve3(int x, int y){
    if(niv[x] < niv[y]) swap(x, y);
    int log1 = 0, log2 = 0;
    while(1 << log1 < niv[x]) log1++;
    while(1 << log2 < niv[y]) log2++;
    for(int p = log1; p >= 0; --p){
        if(niv[x] - (1 << p) >= niv[y])
            x = dp[x][p];
    }
    if(x == y) return x;
    for(int p = log2; p >= 0; --p){
        if(dp[x][p] && dp[x][p] != dp[y][p]){
            x = dp[x][p];
            y = dp[y][p];
        }
    }
    return dp[x][0];

}

int main()
{
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    int m;
    fin >> n >> m;
    for(int i = 2; i <= n; ++i){
        fin >> anc[i];
        graf[anc[i]].push_back(i);
    }
    prec();
    while(m){
        int x, y;
        fin >> x >> y;
        fout << solve3(x, y) << "\n";
        m--;
    }
    return 0;
}