Pagini recente » Cod sursa (job #1712858) | Cod sursa (job #1880323) | Cod sursa (job #1377404) | Cod sursa (job #2149608) | Cod sursa (job #3214936)
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 100000
int n, m, t, L;
vector <int> tin, tout;
vector <vector <int> > graph, up;
bitset <MAX_N + 1> viz;
void dfs(int node, int parent)
{
tin[node] = ++t;
viz[node] = 1;
up[0][node] = parent;
for(int i = 1; i <= L ; i ++)
up[i][node] = up[i - 1][up[i - 1][node]];
for(int x : graph[node])
if(!viz[x])
dfs(x, node);
tout[node] = ++t;
}
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;
int u = a;
for(int i = L; i >= 0; i --)
{
if(!isAncestor(up[i][u], b))
u = up[i][u];
}
return up[0][u];
}
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);
for(int i = 2; i <= n; i ++)
{
int x;
cin >> x;
graph[x].push_back(i);
graph[i].push_back(x);
}
L = log2(n);
up.resize(L + 1, vector <int> (n + 1));
tin.resize(n + 1);
tout.resize(n + 1);
dfs(1, 1);
for(int i = 1; i <= m; i ++)
{
int a, b;
cin >> a >> b;
cout << lca(a, b) << "\n";
}
return 0;
}