Cod sursa(job #3364058)

Utilizator Andrei_GAndreiG Andrei_G Data 28 august 2026 17:35:45
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <iostream>
#pragma GCC optimize("O3,unroll-loops")
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <iomanip>
#include <numeric>
#include <cstdio>
#include <bitset>
#include <string>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#define int long long
//#define int short
using namespace std;

const int nmax = 1e5;
const int lg = 17;

int n, m, spt[nmax + 5][lg + 1], depth[nmax + 5];
vector<int> adj[nmax + 5];

struct LCA{
    LCA(){
        dfs(0, 1);
        sptbuild();
    }

    void dfs(int p, int u){
        depth[u] = depth[p] + 1;
        spt[u][0] = p;
        for (auto& v : adj[u]){
            dfs(u, v);
        }
    }

    void sptbuild(){
        for (int j = 1; j <= lg; j++){
            for (int i = 1; i <= n; i++){
                spt[i][j] = spt[spt[i][j - 1]][j - 1];
            }
        }
    }

    int lca(int u, int v){
        if (depth[u] < depth[v]){
            swap(u, v);
        }

        for (int bit = lg; bit >= 0; bit--){
            if (depth[u] - (1 << bit) >= depth[v]){
                u = spt[u][bit];
            }
        }
        if (u == v){
            return u;
        }
        for (int bit = lg; bit >= 0; bit--){
            if (spt[u][bit] != spt[v][bit]){
                u = spt[u][bit];
                v = spt[v][bit];
            }
        }
        return spt[u][0];
    }
};

signed main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    freopen("lca.in", "r", stdin);
    freopen("lca.out", "w", stdout);
    cin>>n>>m;
    for (int i = 1; i < n; i++){
        int x; cin>>x;
        adj[x].push_back(i + 1);
    }
    LCA idk = LCA();
    while (m--){
        int u, v;
        cin>>u>>v;
        cout<<idk.lca(u, v)<<"\n";
    }
}