Pagini recente » Cod sursa (job #2185799) | Cod sursa (job #1624606) | Cod sursa (job #2408009) | Cod sursa (job #965344) | Cod sursa (job #2700474)
//ALEXANDRU MICLEA
//solutie cu dinamica de la stramosi / sparse table
//O(n log n) precalculare, O(1) raspuns
#include <vector>
#include <algorithm>
#include <string>
#include <string.h>
#include <cstring>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>
#include <random>
#include <chrono>
#include <assert.h>
#include <iostream>
using namespace std;
using ll = long long;
#define fast_cin() ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
//VARIABLES
int dp[25][400005];
int LOG[400005];
vector <int> euler;
int pos[100005];
int h[100005];
vector <int> gr[100005];
//FUNCTIONS
void dfs(int nod) {
euler.push_back(nod);
pos[nod] = euler.size() - 1;
for (auto& x : gr[nod]) {
h[x] = h[nod] + 1;
dfs(x);
euler.push_back(nod);
}
}
//MAIN
int main() {
#ifdef INFOARENA
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
#endif
fast_cin();
int n, m; cin >> n >> m;
for (int i = 2; i <= n * 2; i++) LOG[i] = LOG[i / 2] + 1;
for (int i = 2; i <= n; i++) {
int val; cin >> val;
gr[val].push_back(i);
}
dfs(1);
for (int i = 0; i < euler.size(); i++) {
dp[0][i] = euler[i];
}
for (int p = 1; p <= LOG[2 * n]; p++) {
for (int i = 0; i < euler.size(); i++) {
if (h[dp[p - 1][i]] < h[dp[p - 1][i + (1 << (p - 1))]]) {
dp[p][i] = dp[p - 1][i];
}
else {
dp[p][i] = dp[p - 1][i + (1 << (p - 1))];
}
}
}
for (int i = 1; i <= m; i++) {
int x, y; cin >> x >> y;
x = pos[x];
y = pos[y];
if (x > y) swap(x, y);
int dif = y - x + 1;
int dist = LOG[dif];
if (h[dp[dist][x]] < h[dp[dist][y - (1 << dist) + 1]]) cout << dp[dist][x];
else cout << dp[dist][y - (1 << dist) + 1];
cout << '\n';
}
return 0;
}