Cod sursa(job #2654680)

Utilizator drknss_Hehe hehe drknss_ Data 1 octombrie 2020 21:34:34
Problema Lowest Common Ancestor Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 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, first[N], last[N], E[N], x;
vector<int>v[N];

void dfs(int nod,int p,int d){
	pr[nod] = p;
	depth[nod] = d;
	for(auto it: v[nod]){
		if(it==p)continue;
		dfs(it,nod,d+1);
	}
	E[++x] = nod;
}

int is_ancestor(int x, int y){
    if(first[x] < first[y] && last[y] < last[x])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 j = 20; j >= 0; j--){
		if(dp[x][j] && !is_ancestor(x, y)){
			x = dp[x][j];
		}
	}
	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,1);

	for(int i = 1; i <= x; i++){
        if(!first[E[i]])first[E[i]] = i;
        last[E[i]] = i;
	}

	for(int i = 1; i <= n; i++){
		dp[i][0] = pr[i];
	}

	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;

		if(depth[x]<depth[y])swap(x,y);

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

	}
return 0;
}