Cod sursa(job #2870521)

Utilizator 100pCiornei Stefan 100p Data 12 martie 2022 13:38:33
Problema Lowest Common Ancestor Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>
#define FILES freopen("lca.in","r",stdin);\
              freopen("lca.out","w",stdout);
#define fastio ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL);
#define MAX 100000
#define pb push_back
#define mp make_pair
using namespace std;
int n,q,a,f[MAX+5],x,y;
bool check[MAX+5];
vector<int>v[MAX+5];
vector<pair<int,int>> euler,rmq[20];
void dfs(int x,int h)
{
    check[x] = 1;
    euler.pb({x,h});
    f[x] = euler.size();
    for(auto i : v[x])
    {
        if(!check[i])
        {
            dfs(i,h+1);
            euler.pb({x,h});
        }
    }
}
void read(int &a)
{
    char c;
    a = 0;
    while(1)
    {
        c = getchar();
        if(c < '0' || c > '9') break;
        a = a * 10 + c - '0';
    }
}
pair<int,int> Min(pair<int,int> a,pair<int,int> b)
{
    return (a.second > b.second ? b : a);
}
int main()
{
    FILES
    read(n),read(q);
    for(int i = 1;i < n; ++i)
    {
        read(a);
        v[a].pb(i+1),v[i+1].pb(a);
    }
    dfs(1,1);
    for(int i = 0;i < euler.size(); ++i) rmq[0].pb({euler[i].first,euler[i].second});
    int tot = euler.size(), sz = log2(euler.size());
    for(int i = 1;i <= sz; ++i)
    {
        tot -= (1 << (i - 1));
        for(int j = 1;j <= tot; ++j)
            rmq[i].pb(Min(rmq[i-1][j-1],rmq[i-1][j-1+(1<<(i-1))]));
    }
    for(int i = 1;i <= q; ++i)
    {
        cin >> x >> y;
        int mx = max(f[x],f[y]), mn = min(f[x],f[y]);
        int d = mx - mn + 1, p = 1, e = 0;
        while(p <= d) p *= 2,e++;
        p >>= 1,e--;
        cout << Min(rmq[e][mn-1],rmq[e][mx-p]).first << '\n';
    }
}