Pagini recente » Cod sursa (job #1947684) | Cod sursa (job #2631177) | Cod sursa (job #2363924) | Cod sursa (job #1504074) | Cod sursa (job #3216328)
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define vpi vector<pii>
#define vvpi vector<vpi>
#define pb push_back
#define eb emplace_back
using namespace std;
const string TASK("lca");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout
const int N = 1e5 + 9, LG = 19;
int n, m, t[N][LG], dep[N];
vvi G(N);
void Dfs(int x = 1)
{
for(int i = 1; i < LG; ++i)
t[x][i] = t[t[x][i - 1]][i - 1];
for(auto y : G[x])
{
dep[y] = dep[x] + 1;
Dfs(y);
}
}
int get_lca(int x, int y)
{
if(dep[x] < dep[y])swap(x, y);
for(int i = LG - 1; i >= 0; --i)
if(dep[x] - (1 << i) >= dep[y])
x = t[x][i];
if(x == y)return x;
for(int i = LG - 1; i >= 0; --i)
if(t[x][i] != t[y][i])
{
x = t[x][i];
y = t[y][i];
}
return t[x][0];
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
cin >> n >> m;
for(int i = 2; i <= n; ++i)
{
cin >> t[i][0];
G[t[i][0]].pb(i);
}
Dfs();
int x, y;
for(int i = 1; i <= m; ++i)
{
cin >> x >> y;
cout << get_lca(x, y) << '\n';
}
return 0;
}