Cod sursa(job #2441484)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 20 iulie 2019 15:42:38
Problema Lowest Common Ancestor Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005, RAD = 316;

int n;
int anc[MAXN], radanc[MAXN];

int solve1(int x, int 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 solve2(int x, int y){
    while(x != y && x != anc[y] && y != anc[x]){
        if(x > y){
            if(x - y < RAD) x = anc[x];
            else x = radanc[x];
        }
        else if(x < y){
            if(y - x < RAD) y = anc[y];
            else y = radanc[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;
    anc[1] = 1;
    for(int i = 2; i <= n; ++i)
        fin >> anc[i];
    for(int i = 2; i <= n; ++i){
        int cnt = 0, str = i;
        while(str < 1 && cnt < RAD){
            str = anc[str];
            cnt++;
        }
        if(cnt == RAD) radanc[i] = str;
    }
    while(m){
        int x, y;
        fin >> x >> y;
        fout << solve2(x, y) << "\n";
        m--;
    }
    return 0;
}