Cod sursa(job #3156727)

Utilizator Horia_haivasHaivas Horia Horia_haivas Data 12 octombrie 2023 18:56:45
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
/*
    "care a facut teste cu Lattice reduction attack e ciudat"
    - 2023 -
*/
#include<bits/stdc++.h>
#define debug(x) cerr << #x << " " << x << "\n"
#define debugs(x) cerr << #x << " " << x << " "
#pragma GCC optimize("Ofast")

using namespace std;

vector<int> children[100001];
int up[17][100001];
int depth[100001];

void dfs(int node)
{
    int j;
    for (j=0;j<children[node].size();j++)
    {
         depth[children[node][j]]=depth[node]+1;
         dfs(children[node][j]);
    }
}

int lca(int a, int b)
{
    if (depth[a]<depth[b])
        swap(a,b);
    int k,j;
    k=depth[a]-depth[b];
    for (j=0;j<=16;j++)
    {
         if (k&(1<<j))
         {
             a=up[j][a];
         }
    }
    if (a==b)
        return a;
    for (j=16;j>=0;j--)
    {
         if (up[j][a]!=up[j][b])
         {
             a=up[j][a];
             b=up[j][b];
         }
    }
    return up[0][a];
}

int main()
{
    ifstream fin("lca.in");
    ofstream fout("lca.out");
    ios_base::sync_with_stdio(false);
    cin.tie();
    cout.tie();
    int n,q,i,j,x,a,b;
    fin >> n >> q;
    for (j=2;j<=n;j++)
    {
         fin >> x;
         children[x].push_back(j);
         up[0][j]=x;
    }
    up[0][j]=0;
    for (j=1;j<=16;j++)
    {
         for (i=1;i<=n;i++)
         {
              up[j][i]=up[j-1][up[j-1][i]];
         }
    }
    depth[1]=1;
    dfs(1);
    for (j=1;j<=q;j++)
    {
         fin >> a >> b;
         fout << lca(a,b) << "\n";
    }
    return 0;
}