Cod sursa(job #2970841)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 25 ianuarie 2023 23:04:09
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
/*
 * O(Q * N)
 */
#include <fstream>
#include <vector>
using namespace std;

const int MAX_N = 100005;

int N, Q;
vector<int> arbore[MAX_N];
int parinte[MAX_N], nivel[MAX_N];

void dfs(int nod, int nvl = 1)
{
    nivel[nod] = nvl;
    for (int fiu : arbore[nod])
    {
        dfs(fiu, nvl + 1);
    }
}

int lca(int x, int y)
{
    if (nivel[x] < nivel[y])
    {
        swap(x, y);
    }
    while (nivel[x] > nivel[y])
    {
        x = parinte[x];
    }
    while (x != y)
    {
        x = parinte[x];
        y = parinte[y];
    }
    return x;
}

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

    fin >> N >> Q;
    for (int nod = 2; nod <= N; ++nod)
    {
        fin >> parinte[nod];
        arbore[parinte[nod]].push_back(nod);
    }

    dfs(1);

    while (Q--)
    {
        int x, y;
        fin >> x >> y;
        fout << lca(x, y) << "\n";
    }

    return 0;
}