Cod sursa(job #3291187)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 3 aprilie 2025 15:36:55
Problema Lowest Common Ancestor Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, dp[17][100001], level[100001]; /// dp[i][j] = al 2^i-lea stramos al nodului j
vector <int> L[100001];

int KthAncestor(int k, int nod)
{
    int ans = nod;
    for (int i = 0; (1 << i) <= k; i++)
        if ((1 << i) & k)
            ans = dp[i][ans];
    return ans;
}

void DFS(int nod)
{
    for (auto next : L[nod])
    {
        level[next] = 1 + level[nod];
        DFS(next);
    }
}

int LCA(int nod1, int nod2)
{
    int st = 0, dr = min(level[nod1], level[nod2]), ans = 1;
    while (st <= dr)
    {
        int mid = (st + dr) / 2;
        int v1 = KthAncestor(level[nod1] - mid, nod1);
        int v2 = KthAncestor(level[nod2] - mid, nod2);
        if (v1 == v2)
        {
            ans = v1;
            st = mid + 1;
        }
        else dr = mid - 1;
    }
    return ans;
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i < n; i++) {
        fin >> dp[0][i + 1];
        L[dp[0][i + 1]].push_back(i + 1);
    }
    DFS(1);
    for (int i = 1; (1 << i) <= n; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = dp[i - 1][dp[i - 1][j]];
    while (m--)
    {
        int nod1, nod2;
        fin >> nod1 >> nod2;
        fout << LCA(nod1, nod2) << "\n";
    }
    return 0;
}