Cod sursa(job #2763385)

Utilizator VanillaSoltan Marian Vanilla Data 13 iulie 2021 15:54:07
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.3 kb
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
typedef long long int64;
typedef vector<int> vec;
typedef vector<int64> vec64;
  string __fname = "lca";
  ifstream in (__fname + ".in");
  ofstream out (__fname + ".out");
  #define cin in
  #define cout out
#define pii pair <int, int> 
#define pii64 pair <int64, int64>
#define ss cout << " ";
#define nn cout << "\n";
#define ct(x) cout << x;
#define cts(x) cout << x << " ";
#define ctn(x) cout << x << "\n";
#define db(x) cout << "> " << #x << ": " << x << "\n";
#define qr queries();
void solve(int);
void queries(){int n;cin >> n;for (int i = 1; i <= n; i++) solve(i);}
int64 ceildiv(int64 a, int64 b) {return a / b + !!(a % b);}
template<class T>T gcd (T a, T b){return (b ? gcd(b, a % b): a);}
template<class T>T lcm (T a, T b){return a * b / gcd(a, b);}
// // // // // // // // // // // // // // // // // // // // // // 
/*                  TEMPLATE - VANILLA                         */
// // // // // // // // // // // // // // // // // // // // // //
const int maxn = 200200;
const int64 mod = 1000000007;
const double pi = 3.14159265359;
const int ddx[] = {-1, -1, 0, 1, 1, 1, 0, -1};
const int ddy[] = {0, 1, 1, 1, 0, -1, -1, -1};
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, 1, 0, -1};
const int lg = 18;
vec a [maxn];
vector <int> depth (maxn);
vector <int> vz (maxn);
int up[maxn][lg];

void solve(int id){

    return;
}

void dfs (int u) {
    for (auto v: a[u]) {
        depth[v] = depth[u] + 1;
        up[v][0] = u;
        for (int i = 1; i < lg; i++){
            up[v][i] = up[up[v][i-1]][i-1];
        }
        dfs(v);
    }
}

int lca (int x, int y) {
    if (depth[x] < depth[y]) {
        swap(x, y);
    }
    int k = depth[x] - depth[y];
    for (int i = 0; i < lg; i++){
        if (k & (1 << i)) {
            x = up[x][i];
        }
    }
    if (x == y) return x;
    for (int i = lg - 1; i >= 0; i--) {
        if (up[x][i] != up[y][i]) {
            x = up[x][i];
            y = up[y][i];
        }
    }
    return up[x][0];
}

int main(){
    ios_base::sync_with_stdio(0);cin.tie(0);
    int n,q;
    cin >> n >> q;
    for (int i = 0; i < n - 1; i++){
        int x;
        cin >> x;
        a[x].push_back(i + 2);
    }
    dfs(1);
    while (q--) {
        int x,y;
        cin >> x >> y;
        ctn(lca(x,y));
    }
    return 0;
}