Cod sursa(job #2418971)

Utilizator Leonard123Mirt Leonard Leonard123 Data 7 mai 2019 10:18:03
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <math.h>
using namespace std;
#define maxn 100005
int father[maxn],p[maxn],level[maxn],n,m,nod,r,son[1][maxn];

ifstream cin("lca.in");
ofstream cout("lca.out");

void LCA(int x, int y){
    while(p[x]!=p[y]){
        if(level[x]>level[y])
            x=p[x];
        else y=p[y];
    }
    while(x!=y){
        if(level[x]>level[y])
            x=father[x];
        else y=father[y];
    }
    cout<<x<<'\n';

}

void dfs(int no){
    if(level[no]<r)
        p[no]=1;
    else  if(!(level[no]%r))
        p[no]=father[no];
    else p[no]=p[father[no]];
    for(int i=0; i<son[1][no]; i++)
        dfs(son[0][no]+i);
}

int main()
{
    level[1]=0;
    father[1]=0;
    p[1]=1;
    cin>>n>>m;
    for(int i=2; i<=n; i++){
        cin>>nod;
        if(!son[0][nod])
            son[0][nod]=i;
        son[1][nod]++;
        father[i]=nod;
        level[i]=level[father[i]]+1;
        if(level[i]>r) r=level[i];
    }
    r=sqrt(r);
    dfs(1);
    int x,y;
    for(int i=1; i<=m; i++){
            cin>>x>>y;
            LCA(x,y);
    }
    return 0;
}