Cod sursa(job #2685164)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 16 decembrie 2020 10:22:12
Problema Lowest Common Ancestor Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.32 kb
#include <bits/stdc++.h>
using namespace std;
void debug_out() { cerr << endl; }
template<class T> ostream& prnt(ostream& out, T v) { out << v.size() << '\n'; for(auto e : v) out << e << ' '; return out;}
template<class T> ostream& operator<<(ostream& out, vector <T> v) { return prnt(out, v); }
template<class T> ostream& operator<<(ostream& out, set <T> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, map <T1, T2> v) { return prnt(out, v); }
template<class T1, class T2> ostream& operator<<(ostream& out, pair<T1, T2> p) { return out << '(' << p.first << ' ' << p.second << ')'; }
template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << H; debug_out(T...);}
#define dbg(...) cerr << #__VA_ARGS__ << " ->", debug_out(__VA_ARGS__)
#define dbg_v(x, n) do{cerr<<#x"[]: ";for(int _=0;_<n;++_)cerr<<x[_]<<" ";cerr<<'\n';}while(0)
#define dbg_ok cerr<<"OK!\n"
#define ll long long
#define ld long double
#define ull unsigned long long
#define pii pair<int,int>
#define MOD 1000000007
#define zeros(x) x&(x-1)^x
#define fi first
#define se second
#define NMAX 100005
const long double PI = acos(-1);

int n,m;
vector<int> v[NMAX];


#define K 18
int height[NMAX], fth[K][NMAX];

void dfs_LCA(int nod, int ant = 0, int h = 1){
  height[nod] = h;
  fth[0][nod] = ant; 
  for (auto it : v[nod]){
    if (it == ant) continue;
    dfs_LCA(it, nod, h+1);
  }
}

int LCA(int a, int b){
  if (height[a] > height[b]) swap(a,b);
  for (int i=K-1;i>=0;i--) if (height[b] - (1<<i) >= height[a]){
    b = fth[i][b];
    
  }
  for (int i=K-1;i>=0;i--) if (fth[i][b] != fth[i][a]) a = fth[i][a], b = fth[i][b];

  if (a == b) return a;
  return fth[0][a];
}

// binary lifting
int goUp(int a, int k){
  for (int i=K-1;i>=0;i--) if (k >= (1<<i)) a = fth[i][a], k -= (1<<i);
  return a;
}

// apeleaza asta inainte
int build_LCA(int root = 1){
  dfs_LCA(root);
  for (int i=1;i<K;i++)
    for (int j=1;j<=n;j++){
      fth[i][j] = fth[i-1][fth[i-1][j]];
    }
}

int main(){
  ios::sync_with_stdio(false);
  freopen("lca.in","r",stdin);
  freopen("lca.out","w",stdout);

  scanf("%d%d", &n, &m);

  for (int i=2;i<=n;i++){
    int x;
    scanf("%d",&x);
    v[x].push_back(i);
  }

  build_LCA();

  for (int i=1;i<=m;i++){
    int a,b;
    scanf("%d%d",&a, &b);
    cout << LCA(a,b) << '\n';
  }


  return 0;
}