Cod sursa(job #2392252)

Utilizator ezioconnorVlad - Gabriel Iftimescu ezioconnor Data 29 martie 2019 20:30:40
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

const int SIZE = 320;
int n, m, v[100001];
int l[100001], father[100001];
vector <int> Muchii[100001];

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

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

inline int lca(int x, int y)
{
    while (father[x] != father[y])
    {
        if (l[x] > l[y])
            x = father[x];
        else
            y = father[y];
    }
    while (x != y)
    {
        if (l[x] > l[y])
            x = father[x];
        else
            y = father[y];
    }
    return x;
}

int main()
{
    int x, y;
    citire();
    DFS(1, 0, 0);
    for (int q = 1; q <= m; ++q)
    {
        in >> x >> y;
        out << lca(x, y) << '\n';
    }
    return 0;
}