Pagini recente » Cod sursa (job #830844) | Cod sursa (job #2267155) | Cod sursa (job #1619340) | Cod sursa (job #1785439) | Cod sursa (job #3215150)
#include <bits/stdc++.h>
using namespace std;
const int max_size = 1e5 + 20, rmax = 22;
int lvl[max_size], poz[max_size], rmq[rmax][2 * max_size], lg[2 * max_size], timp;
vector <int> mc[max_size];
void dfs (int nod)
{
timp++;
poz[nod] = timp;
rmq[0][timp] = nod;
for (auto f : mc[nod])
{
lvl[f] = lvl[nod] + 1;
dfs(f);
rmq[0][++timp] = nod;
}
}
bool cmp (int x, int y)
{
return lvl[x] < lvl[y];
}
void solve ()
{
int n, q;
cin >> n >> q;
for (int i = 2; i <= n; i++)
{
int x;
cin >> x;
mc[x].push_back(i);
}
dfs(1);
for (int i = 2; i <= timp; i++)
{
lg[i] = lg[i / 2] + 1;
}
for (int e = 1; e < rmax; e++)
{
for (int i = 1; i + (1 << e) - 1 <= timp; i++)
{
rmq[e][i] = min(rmq[e - 1][i], rmq[e - 1][i + (1 << (e - 1))], cmp);
}
}
while (q--)
{
int x, y;
cin >> x >> y;
x = poz[x];
y = poz[y];
if (x > y)
{
swap(x, y);
}
int diff = y - x + 1, e = lg[diff];
cout << min(rmq[e][x], rmq[e][y - (1 << e) + 1], cmp) << '\n';
}
cout << '\n';
}
signed main ()
{
#ifdef LOCAL
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
#else
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
#endif // LOCAL
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
long long tt;
//cin >> tt;
tt = 1;
while (tt--)
{
solve();
}
return 0;
}