Cod sursa(job #2397140)

Utilizator T_george_TGeorge Teodorescu T_george_T Data 4 aprilie 2019 11:04:01
Problema Lowest Common Ancestor Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
#define NMAX 100005
#define LMAX 20
int n,m,father[LMAX][NMAX],Lg[NMAX],depth[NMAX];
vector<int>g[NMAX];
int papa(int node,int x){
    for(int i=0;(1<<i)<=x;i++){
        if(x&(1<<i))
            node=father[i][node];
    }
    return node;
}
void dfs(int node,int papa){
    depth[node]=depth[papa]+1;
    for(auto y:g[node]){
        if(y!=papa)
            dfs(y,node);
    }
}
int lca(int x,int y){
    if(depth[x]<depth[y])
        swap(x,y);
    int k=depth[x]-depth[y],log;
    x=papa(x,k);
    if(x==y)
        return x;
        for(log=1;(1<<log)<depth[y]; ++log);
    for(int i=log;i>=0;i--){
        if(father[i][x]!=father[i][y]){
            x=father[i][x];
            y=father[i][y];
        }
    }
    return father[0][x];
}
int main()
{
    in>>n>>m;
    for(int i=2;i<=n;i++){
        in>>father[0][i];
        g[father[0][i]].push_back(i);
    }
    for(int k=1;(1<<k)<=n;k++){
    for(int i=1;i<=n;i++)
        father[k][i]=father[k-1][father[k-1][i]];
    }
    dfs(1,0);
    for(int i=1;i<=m;i++){
        int st,dr;
        in>>st>>dr;
        out<<lca(st,dr)<<endl;
    }
    return 0;
}