Cod sursa(job #2086406)

Utilizator chiscanuChiscu Razvan chiscanu Data 12 decembrie 2017 00:35:05
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>

using namespace std;

const int h = 200;

int N, M, tata[100010], interval[100010], nivel[100010];
vector <int> G[100010];

void dfs(int nod, int n1, int lev)
{
    nivel[nod] = lev;
    interval[nod] = n1;

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

    for (vector<int>::iterator it = G[nod].begin(); it != G[nod].end(); ++it) {
        dfs(*it, n1, lev + 1);
    }
}

int lca(int x, int y)
{
    while(interval[x] != interval[y]) {
        if(nivel[x] > nivel[y])
            x = interval[x];
        else
            y = interval[y];
    }

    while(x != y) {
        if(nivel[x] > nivel[y])
            x = tata[x];
        else
            y = tata[y];
    }
    return x;
}

int main()
{
    ifstream in ("lca.in");
    ofstream out ("lca.out");

    in >> N >> M;

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

    dfs(1, 0, 0);

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

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