Pagini recente » Cod sursa (job #294418) | Cod sursa (job #2060482) | Cod sursa (job #502752) | Cod sursa (job #1372242) | Cod sursa (job #3041326)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define MAX_N 100000
int n, m, timer, L;
vector <int> tin, tout;
vector <vector <int> > graph, up;
void dfs(int node, int parent)
{
tin[node] = ++timer;
up[node][0] = parent;
for(int i = 1; i <= L; i ++)
up[node][i] = up[up[node][i - 1]][i - 1];
for(int neighbour : graph[node])
{
if(neighbour != parent)
dfs(neighbour, node);
}
tout[node] = ++timer;
}
bool isAncestor(int a, int b)
{
return tin[a] <= tin[b] && tout[b] <= tout[a];
}
int lca(int a, int b)
{
if(isAncestor(a, b))
return a;
if(isAncestor(b, a))
return b;
for(int i = L; i >= 0; i --)
if(!isAncestor(up[a][i], b))
a = up[a][i];
return up[a][0];
}
int main()
{
ios_base :: sync_with_stdio(0);
cin.tie(0);
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
cin >> n >> m;
graph.resize(n + 1);
tin.resize(n + 1);
tout.resize(n + 1);
L = ceil(log2(n));
up.assign(n + 1, vector<int>(L + 1));
for(int i = 2; i <= n; i++)
{
int x;
cin >> x;
graph[x].pb(i);
}
dfs(1, 1);
for(int i = 1; i <= m; i ++)
{
int a, b;
cin >> a >> b;
cout << lca(a, b) << "\n";
}
return 0;
}