Cod sursa(job #2365619)

Utilizator moltComan Calin molt Data 4 martie 2019 15:15:56
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MOD = 317;

vector<int> v[100005];
int niv[100005], tmare[100005], t[100005];
int n, nrq;

void DFS(int nod, int ant, int nivel)
{
    niv[nod] = nivel;
    tmare[nod] = ant;
    if (nivel % MOD == 0) ant = nod;
    for (int i = 0;i < v[nod].size();++i)
    {
        DFS(v[nod][i], ant, nivel + 1);
    }
}

int main()
{
    in>>n>>nrq;
    for (int i = 2;i <= n;++i)
    {
        in>>t[i];
        v[t[i]].push_back(i);
    }
    DFS(1, 0, 0);
    while (nrq--)
    {
        int x,y;
        in>>x>>y;
        while (tmare[x] != tmare[y])
        {
           if (niv[x] > niv[y]) x = tmare[x];
           else y = tmare[y];
        }
        while (x != y)
        {
            if (niv[x] > niv[y]) x = t[x];
            else y = t[y];
        }
        out<<x<<"\n";
    }
    return 0;
}