Cod sursa(job #2441455)

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

using namespace std;

const int MAXN = 100005;

int n;
int anc[MAXN];

int solve1(int x, int y){
    int strx = anc[x], stry = anc[y];
    while(strx != stry){
        if(strx > stry) strx = anc[strx];
        else if(strx < stry) stry = anc[stry];
    }
    return strx;
}

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];
    while(m){
        int x, y;
        fin >> x >> y;
        if(x == anc[y] || y == anc[x] || x == y){
            if(x == anc[y]) fout << x << "\n";
            else fout << y << "\n";
            m--;
            continue;
        }
        fout << solve1(x, y) << "\n";
        m--;
    }
    return 0;
}