Cod sursa(job #2721054)

Utilizator victorzarzuZarzu Victor victorzarzu Data 11 martie 2021 15:30:50
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
int n, k, x, y, nivel[100005], size[100005], heavy[100005], lant[100005], t[100005];
vector<int> graf[100005];

void Read()
{
  f>>n>>k;
  for(int i = 2;i <= n;++i)
    f>>t[i], graf[t[i]].push_back(i);
}

void dfs(int nod, int parinte)
{
  size[nod] = 1;
  nivel[nod] = nivel[parinte] + 1;
  int maxim = 0;
  for(auto it : graf[nod])
    {
      dfs(it, nod);
      size[nod] += size[it];
      if(maxim < size[it])
        maxim = size[it], heavy[nod] = it;
    }
}

void compose(int nod, int root)
{
  lant[nod] = root;
  if(heavy[nod])
    compose(heavy[nod], root);
  for(auto it : graf[nod])
    if(it != heavy[nod])
      compose(it, it);
}

int lca(int x, int y)
{
  while(lant[x] != lant[y])
  {
    if(nivel[lant[x]] < nivel[lant[y]]) swap(x, y);
    x = t[lant[x]];
  }
  return (nivel[x] > nivel[y] ? y : x);
}

void Solve()
{
  dfs(1, 0);
  compose(1, 1);
  for(int i = 1;i <= k;++i)
    f>>x>>y, g<<lca(x, y)<<'\n';
}

int main()
{
  Read();
  Solve();
  return 0;
}