Pagini recente » Cod sursa (job #283825) | Cod sursa (job #1354950) | Cod sursa (job #1158720) | Cod sursa (job #1059827) | Cod sursa (job #2832542)
#include <bits/stdc++.h>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int a, int b)
{
int ans = uniform_int_distribution<int>(a, b)(rng);
return ans;
}
#define fastio std::ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
#define test " test "
#define yes "YES"
#define no "NO"
#define bn '\n'
#define ll long long
#define pb push_back
#define mp make_pair
//#define int long long
#define deb(a) cout << #a << "=" << (a) << bn
#define deb2(a, b) cout << #a << "=" << (a) << " " << #b << "=" << b << bn
#define readV(v, n) \
for (int i = 0; i < n; i++) \
cin >> v[i];
#define printV(v) \
for (auto i : v) \
cout << i << " ";
#define FILES \
freopen("lca.in", "r", stdin); \
freopen("lca.out", "w", stdout);
const int mod = 1e9 + 7;
const int MAXN = 100000;
const int LOG = 17;
int n, m;
int root = 1;
int up[MAXN][LOG];
int depth[MAXN];
vector<int> children[MAXN];
int lca(int a, int b)
{
if (depth[a] < depth[b])
swap(a, b);
int k = depth[a] - depth[b];
for (int j = LOG - 1; j >= 0; j--)
if (k & (1 << j))
a = up[a][j];
if (a == b)
return a;
for (int j = LOG - 1; j >= 0; j--)
if (up[a][j] != up[b][j])
{
a = up[a][j];
b = up[b][j];
}
return up[a][0];
}
void dfs(int node)
{
for (int v : children[node])
{
up[v][0] = node;
depth[v] = depth[node] + 1;
for (int j = 1; j < LOG; j++)
up[v][j] = up[up[v][j - 1]][j - 1];
dfs(v);
}
}
void solve()
{
cin >> n >> m;
int x;
for (int i = 2; i <= n; i++)
{
cin >> x;
children[x].pb(i);
}
dfs(1);
for (int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
cout << lca(u, v) << bn;
}
}
signed main()
{
fastio;
FILES;
int __t = 1;
// cin >> __t;
while (__t--)
solve();
return 0;
}