Cod sursa(job #2654685)

Utilizator drknss_Hehe hehe drknss_ Data 1 octombrie 2020 21:41:45
Problema Lowest Common Ancestor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define all(a) (a).begin(), (a).end()
#define forn(i,a,b) for (int i = a; i <= b; i++)
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define rc(s) return cout<<s,0
#define rcc(s) cout<<s,exit(0)
#define er erase
#define in insert
#define pi pair <int, int>
# define sz(x) (int)((x).size())
//#define int long long

const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};

const ll inf = 0x3f3f3f3f3f3f3f;
const int N = 2e5 + 11;

ifstream in("lca.in");
ofstream out("lca.out");

int n, k, pr[N], depth[N], dp[N][25], node[N], t, m, tin[N], tout[N];
vector<int>v[N];

void dfs(int nod, int p){

    tin[nod] = ++t;
    dp[nod][0] = p;

    for(auto it : v[nod]){
        if(it == p)continue;
        dfs(it, nod);
    }

    tout[nod] = ++t;
}

bool is_ancestor(int p, int x){
    if(tin[p] <= tin[x] && tout[x] <= tout[p]) return 1;
    return 0;
}

int lca(int x, int y){
    if(is_ancestor(x,y))return x;
    if(is_ancestor(y,x))return y;
    for(int i = 20; i >= 0; i--){
        if(!is_ancestor(dp[x][i], y) && dp[x][i] != 0)x = dp[x][i];
    }
    return dp[x][0];
}

int32_t main(){
ios_base::sync_with_stdio(0); cin.tie(0); cerr.tie(0); cout.tie(0);

	in>>n>>m;

	for(int i = 2,x; i <= n; i++){
		in>>x;
		dp[0][i]=x;
		v[x].pb(i);
	}

	dfs(1, 0);

	for(int j = 1; j <= 20; j++){
		for(int i = 1; i <= n; i++){
			dp[i][j] = dp[dp[i][j-1]][j-1];
		}
	}


	for(int jj = 1, x, y; jj <= m; jj++){

		in>>x>>y;

		out<<lca(x,y)<<'\n';

	}
return 0;
}