Cod sursa(job #1971161)

Utilizator Corneliu10Dumitru Corneliu Corneliu10 Data 19 aprilie 2017 21:29:07
Problema Lowest Common Ancestor Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <vector>

using namespace std;

#define MAX_N 100005
#define foreach(V) for(typeof (V).begin() it = (V).begin(); it != (V).end(); ++it)

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

const int h = 200;

int N, M, T[MAX_N], T2[MAX_N], Lev[MAX_N];
vector <int> G[MAX_N];

void citire()
{
    fin >> N >> M;

    for(int i = 2; i <= N; ++i)
    {
        fin >> T[i];
        G[T[i]].push_back(i);
    }
}

void dfs(int nod, int n1, int lev)
{
    Lev[nod] = lev;
    T2[nod] = n1;

    if(lev % h == 0) n1 = nod;

    foreach(G[nod])
        dfs(*it, n1, lev+1);
}

int lca(int x, int y)
{
    while(T2[x] != T2[y])
        if(Lev[x] > Lev[y])
            x = T2[x];
        else
            y = T2[y];

    while(x != y)
        if(Lev[x] > Lev[y])
            x = T[x];
        else
            y = T[y];

    return x;
}

int main()
{
    citire();
    dfs(1, 0, 0);

    while(M--)
    {
        int x, y;
        fin >> x >> y;

        fout << lca(x, y) << "\n";
    }
}