Cod sursa(job #3206996)

Utilizator matei__bBenchea Matei matei__b Data 24 februarie 2024 17:42:19
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
#define chad char
#define mod 666013
#define dim 100005
#define lim 1000000
#define INF 1000000000
#define FOR(i,a,b) for(int i=(a); i<=(b); i++)
#define piii pair<int,pair<int,int> > 
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pb push_back
#define mp make_pair
#define nr_biti __builtin_popcount
using namespace std;
 
ifstream fin("lca.in");
ofstream fout("lca.out"); 

int st[30][dim];
int n,m;
vector<int> g[dim];
int h[dim];

void dfs(int nod,int daddy=0)
{
    h[nod]=1+h[daddy];

    for(auto it:g[nod])
    {
        if(it==daddy)
            continue;

        dfs(it,nod);
    }
}

void pre()
{
    for(int i=1; (1<<i)<=n; i++)
        for(int j=1; j<=n; j++)
            st[i][j]=st[i-1][st[i-1][j]];
}

int bl(int nod,int niv)
{
    int z=0;

    while(niv)
    {
        if(niv&1)
            nod=st[z][nod];

        z++;
        niv/=2;
    }

    return nod;
}

int lca(int x,int y)
{
    if(h[x]>h[y])
        swap(x,y);

    int dif=h[y]-h[x];

    y=bl(y,dif);

    if(x==y)
        return x;

    for(int i=20; i>=0; i--)
    {
        if(st[i][x]!=st[i][y])
        {
            x=st[i][x];
            y=st[i][y];
        }
    }

    return st[0][x];
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(nullptr);
    fout.tie(nullptr); 

    fin >> n >> m;

    for(int i=2; i<=n; i++)
    {
        fin >> st[0][i];

        g[i].pb(st[0][i]);
        g[st[0][i]].pb(i);
    }

    dfs(1);

    pre();

    while(m--)
    {
        int x,y;

        fin >> x >> y;

        fout << lca(x,y) << "\n";
    }

    return 0;
}