Cod sursa(job #2418812)

Utilizator Leonard123Mirt Leonard Leonard123 Data 6 mai 2019 15:41:05
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <math.h>
using namespace std;
#define rad 320
#define maxn 100005
int father[maxn],p[rad],level[maxn],n,m,nod,r;

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';8 9

}

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