Cod sursa(job #1968847)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 17 aprilie 2017 21:50:29
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 100005, sq = 310;
vector<int> ls[nmax];
int x, y, n, m,tt[nmax],ttm[nmax],niv[nmax], i;

void dfs(int x, int root) {
    int l = ls[x].size(), i, y;
    niv[x] = niv[tt[x]]+1;
    ttm[x] = root;
    if (niv[x]%sq==0) root = x;
    for (i = 0; i < l; i++)
        dfs(ls[x][i],root);
}

int main() {
    f >> n >> m;
    for (i = 2; i <= n; i++) {
        f >> tt[i];
        ls[tt[i]].push_back(i);
    }
    dfs(1,0);
    for (i = 1; i <= m; i++) {
        f >> x >> y;
        while (ttm[x] != ttm[y])
            if (niv[x] < niv[y])
                y = ttm[y];
            else x = ttm[x];
        while (x != y)
            if (niv[x]<niv[y])
                y = tt[y];
            else x = tt[x];
        g << x << '\n';
    }
}