Cod sursa(job #2323301)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 19 ianuarie 2019 08:43:12
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("lca.in");
ofstream fout("lca.out");

int nivel[100005], m, n, viz[100005], t[100005];
vector<int>L[100005];

void DFS(int nod)
{
    viz[nod] = 1;
    for(auto x : L[nod])
        if(!viz[x])
        {
            nivel[x] = nivel[nod] + 1;
            DFS(x);
        }
}

int lca(int x, int y)
{
    while(nivel[x] > nivel[y])
        x = t[x];

    while(nivel[x] < nivel[y])
        y = t[y];

    while(x != y)
        x = t[x],
        y = t[y];

    return x;
}

int main()
{
    fin >> n >> m;
    for(int i = 2; i <= n; i++)
    {
        fin >> t[i];
        L[t[i]].push_back(i);
    }

    nivel[1] = 1;
    DFS(1);

    int x, y;
    while(m--)
    {
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }
    return 0;
}