Pagini recente » Cod sursa (job #294971) | Cod sursa (job #1008155) | Cod sursa (job #1977632) | Cod sursa (job #2306938) | Cod sursa (job #2940007)
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
using namespace std;
#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
ifstream fin("lca.in");
ofstream fout("lca.out");
#endif
const int NMAX = 1e5+5;
const int LOGN = 18;
int n, m;
int a[NMAX];
int dp[NMAX][LOGN];
int x, y;
vector<int> tree[NMAX];
vector<int> e;
int lv[NMAX];
int pos[NMAX];
int cnt;
void dfs(int x, int l) {
lv[x] = l;
pos[x] = e.size();
for (auto v : tree[x]) {
//e.push_back(x);
cnt++;
dfs(v, l + 1);
}
cnt++;
//e.push_back(x);
}
void precalc() {
dfs(1, 0);
for (int i = 0; i < e.size(); i++)
dp[i][0] = i;
for (int j = 1; (1 << j) <= e.size(); j++) {
for (int i = 0; i + (1 << j) - 1 < e.size(); i++) {
int p1 = dp[i][j - 1];
int p2 = dp[i + (1 << (j - 1))][j - 1];
dp[i][j] = lv[e[p1]] < lv[e[p2]] ? p1 : p2;
}
}
}
int query(int i, int j) {
i = pos[i], j = pos[j];
if (i > j)
swap(i, j);
int k = log2(j - i + 1);
int p1 = e[dp[i][k]];
int p2 = e[dp[j - (1 << k) + 1][k]];
return lv[p1] < lv[p2] ? p1 : p2;
}
int main() {
fin >> n >> m;
int x;
for (int i = 2; i <= n; i++) {
fin >> x;
tree[x].push_back(i);
}
precalc();
return cnt / 10000;
while (m--) {
fin >> x >> y;
fout << query(x, y) << '\n';
}
return 0;
}