Cod sursa(job #2441549)

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

using namespace std;

const int MAXN = 100005;

int n, l, frnod;
int anc[MAXN];
int radanc[MAXN], niv[MAXN];

void dfs(int nod){
    l = max(l, frnod);
    frnod++;
    for(int i = 1; i <= n; ++i){
        if(anc[i] == nod){
            dfs(i);
            frnod--;
        }
    }
}

void batog(int nod, int tata, int nivel){
    radanc[nod] = tata;
    niv[nod] = nivel;
    if(nivel % l == 0) tata = nod;
    for(int i = 1; i <= n; ++i){
        if(anc[i] == nod)
            batog(i, tata, nivel + 1);
    }
}

void prec(){
    dfs(1);
    l++;
    batog(1, 1, 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(x > y) x = radanc[x];
        else if(x < y) y = radanc[y];
    }
    while(x != y && x != anc[y] && y != anc[x]){
        if(x > y) x = anc[x];
        else if(x < y) y = anc[y];
    }
    if(x == y || x == anc[y]) return x;
    else return y;
}

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];
    //prec();
    while(m){
        int x, y;
        fin >> x >> y;
        fout << solve1(x, y) << "\n";
        m--;
    }
    return 0;
}