Cod sursa(job #2787807)

Utilizator TeodorMarciucMarciuc Teodor TeodorMarciuc Data 24 octombrie 2021 01:49:23
Problema Lowest Common Ancestor Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
// ConsoleApplication7.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int n, q, rmq[100005][25], p = 1, lg, ex, pw[100005], x, y, j,ap[100005],cnt=1;
vector<int>mu[1005];
pair<int, int>Oiler[100005];
int putere(int a, int b)
{
    if (b == 0) return 1;
    if (b % 2 == 0)
        return putere(a, b / 2) * putere(a, b / 2);
    else if (b % 2 == 1) return putere(a, b / 2) * putere(a, b / 2) * a;
}
void DFS(int nod, int nivel) {
    Oiler[cnt] = { nod,nivel };
    if (ap[nod] == 0)
        ap[nod] = cnt;
    cnt++;
    for (int i = 0;i < mu[nod].size();i++) {
        DFS(mu[nod][i], nivel + 1);
        Oiler[cnt++] = { nod,nivel };
    }
}
int main()
{
    ifstream cin("lca.in");
    ofstream cout("lca.out");
    cin >> n >> q;
    rmq[1][0] = 1;
    for (int i = 2;i <= n;i++) {
        cin >> x;
        mu[x].emplace_back(i);
        rmq[i][0] = i;
    }
    DFS(1, 1);
    for (int i = 1;i <= n;i++) {
        if (p * 2 <= i)
        {
            ex++;
            p =p* 2;
        }
        pw[i] = ex;
    }
    for (int i = n + 1;i <= cnt;i++)
        rmq[i][0] = i;
    for (j = 1, lg = 2;lg <= cnt;lg *= 2, j++)
        for (int i = 1;i + lg - 1 <= cnt;i++)
            if (Oiler[rmq[i][j - 1]].second < Oiler[rmq[i + lg / 2][j-1]].second)
                rmq[i][j] = rmq[i][j - 1];
            else rmq[i][j] = rmq[i+lg/2][j - 1];
    while (q) {
        q--;
        cin >> x >> y;
        x = ap[x];
        y = ap[y];
        if (x > y) swap(x, y);
        int power = putere(2, pw[y - x + 1]);
        if (Oiler[rmq[x][pw[y - x + 1]]].second < Oiler[rmq[y - power + 1][pw[y - x + 1]]].second)
            cout << Oiler[rmq[x][pw[y - x + 1]]].first<<'\n';
        else cout<<Oiler[rmq[y - power + 1][pw[y - x + 1]]].first<<'\n';
    }
}