Cod sursa(job #2591071)

Utilizator drknss_Hehe hehe drknss_ Data 29 martie 2020 17:34:19
Problema Lowest Common Ancestor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 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;
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);
	}
}

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