Cod sursa(job #2382841)

Utilizator ezioconnorVlad - Gabriel Iftimescu ezioconnor Data 18 martie 2019 18:31:59
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
int dp[100001][18], l[100001];
vector <int> Muchii[100001];

inline void citire()
{
    int x;
    in >> n >> m;
    for (int i = 2; i <= n; ++i)
    {
        in >> x;
        dp[i][0] = x;
        Muchii[x].push_back(i);
    }
}

inline void DFS(int nod, int nivel)
{
    l[nod] = nivel;
    for (int i = 0; i < Muchii[nod].size(); ++i)
    {
        int vecin = Muchii[nod][i];
        DFS(vecin, nivel + 1);
    }
}

int main()
{
    int x, y;
    citire();
    DFS(1, 1);
    for (int j = 1; (1 << j) < n; ++j)
    {
        for (int i = 1; i <= n; ++i)
            dp[i][j] = dp[dp[i][j - 1]][j - 1];
    }
    for (int i = 1; i <= m; ++i)
    {
        in >> x >> y;
        if (l[x] < l[y])
            swap(x, y);
        while (l[x] != l[y])
        {
            int p = 0;
            while (l[dp[x][p + 1]] > l[y])
                ++p;
            x = dp[x][p];
        }
        while (x != y)
        {
            int p = 0;
            while (dp[x][p + 1] != dp[y][p + 1])
                ++p;
            x = dp[x][p];
            y = dp[y][p];
        }
        out << x << '\n';
    }
    return 0;
}