Cod sursa(job #2910061)

Utilizator MerlinTheWizardMelvin Abibula MerlinTheWizard Data 18 iunie 2022 09:57:39
Problema Stramosi Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.17 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n,m;
int LOG;
int up[250005][19],depth[100005];
vector<int> children[100005];
int x,y;
 
void Citire()
{
    f>>n>>m;
}
void dfs(int a)
{   
    for(int i : children[a])
    {
        depth[i] = depth[a]+1;
        up[i][1] = a;
        for(int j=2;j<=LOG;j++)
        {
            up[i][j] = up[up[i][j-1]][j-1];
        }
        dfs(i);
    }
}
int LCA(int a, int b)
{
    if(depth[a]<depth[b])
        swap(a,b);
    int k = depth[a] - depth[b];
    for(int i=LOG;i>=1;i--)
    {
        if(k&(1<<(i-1)))
            a = up[a][i];
    }
    if(a==b)
        return a;
    for(int i = LOG; i>=1;i--)
    {   
        if(up[a][i]  != up[b][i])
        {
            a=up[a][i];
            b=up[b][i];
        }
    }
    return up[a][1];
}
int main()
{
    Citire();
    while(1<<LOG<=n)
        LOG++;
    for(int  i=2;i<=n;i++)
    {
        int x;
        f>>x;
        children[x].push_back(i);
    }
    dfs(1);
    for(int i=1;i<=m;i++)
    {
        f>>x>>y;
        g<<LCA(x,y)<<"\n";
    }
}