Cod sursa(job #2441597)

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

using namespace std;

const int MAXN = 100005;

int n, l = 200, frnod;
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){
    int p = 1 << 20, ans = 0;
    while(p){
       if(dp[x][p + ans] != dp[y][p + ans])
            ans += p;
        p /= 2;
    }
    return dp[x][ans];
}

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 << solve2(x, y) << "\n";
        m--;
    }
    return 0;
}