Cod sursa(job #3351889)

Utilizator Tibi201eweREWR Tibi201 Data 22 aprilie 2026 02:09:13
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define MAXN 100000
#define MAXQ 20000

struct Node{
  std::vector <int> adj;
  int jump,parent,h;
}v[MAXN];

void dfs(int node, int parent, int h){
  v[node].parent=parent;
  v[node].h=h;
  v[node].jump=v[node].parent;
  int j1=v[v[node].parent].jump;
  if(j1!=-1){
    int j1d=(h-1)-v[j1].h;
    int j2=v[j1].jump;
    if(j2!=-1){
      int j2d=v[j1].h-v[j2].h;
      if(j1d==j2d)
        v[node].jump=j2;
    }
  }
  for(auto x : v[node].adj)
    if(x!=parent)
      dfs(x, node, h+1);
}

int lca(int x, int y){
  if(v[x].h<v[y].h)
    std::swap(x, y);
  while(v[x].h>v[y].h){
    if(v[v[x].jump].h<v[y].h)
      x=v[x].parent;
    else
      x=v[x].jump;
  }
  while(x!=y){
    if(v[x].jump!=v[y].jump){
      x=v[x].jump;
      y=v[y].jump;
    }else{
      x=v[x].parent;
      y=v[y].parent;
    }
  }
  return x;
}

int main()
{
    FILE *fin=fopen("lca.in", "r"), *fout=fopen("lca.out", "w");
    int n,q,i,x,y,a,b,lca1,lca2,ans,t1,t2;
    fscanf(fin, "%d%d", &n, &q);
    for(i=0; i<n-1; i++){
      fscanf(fin, "%d", &x);
      v[x-1].adj.push_back(i+1);
    }
    dfs(0, -1, 0);
    for(i=0; i<q; i++){
      fscanf(fin, "%d%d", &a, &b);a--;b--;
      fprintf(fout, "%d\n", lca(a,b)+1);
    }
    return 0;
}