Cod sursa(job #1843098)

Utilizator Walrus21andrei Walrus21 Data 8 ianuarie 2017 04:02:03
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#define N 100001

using namespace std;

int i, n, m, h, s, x, y, L[N], T[N], P[N], o[N];

vector <int> G[N];

void dfh(int v)
{
    for(int i = 0; i < G[v].size(); i++)
    {
        L[G[v][i]] = L[v] + 1;
        if(L[G[v][i]] > h) h = L[G[v][i]];
        dfh(G[v][i]);
    }
}

void dfs(int v)
{
    if(L[v] < s)
        P[v] = 1;
    else
        if(L[v] % s)
            P[v] = P[T[v]];
    else
        P[v] = T[v];
    for(int i = 0; i < G[v].size(); i++)
        dfs(G[v][i]);

}

int main()
{
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(i = 1; i < n; i++)
    {
        scanf("%d", &x);
        G[x].push_back(i + 1);
        T[i + 1] = x;
    }
    dfh(1);
    s = sqrt(h + 1);
    P[1] = 1;
    dfs(1);
    for(int q = 0; q < m; q++)
    {
        scanf("%d %d", &x, &y);
        while(P[x] != P[y])
            if(L[x] > L[y]) x = P[x];
            else y = P[y];
        while(x != y)
            if(L[x] > L[y]) x = T[x];
            else y = T[y];
        printf("%d\n", x);
    }
}