Pagini recente » Cod sursa (job #1270656) | Cod sursa (job #1302548) | Cod sursa (job #1404044) | Cod sursa (job #595524) | Cod sursa (job #1290688)
#include<algorithm>
#include<bitset>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<vector>
using namespace std;
#define dbg(x) (cout<<#x<<" = "<<(x)<<'\n')
#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "lca";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif // HOME
typedef long long int lld;
typedef pair<int, int> PII;
typedef pair<int, lld> PIL;
typedef pair<lld, int> PLI;
typedef pair<lld, lld> PLL;
const int INF = (1LL << 30) - 1;
const lld LINF = (1LL << 60) - 1;
const int dx[] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[] = {0, 1, 0, -1, 1, -1, -1, 1};
const int MOD = 666013;
const int NMAX = 100000 + 5;
const int MMAX = 100000 + 5;
const int KMAX = 100000 + 5;
const int PMAX = 100000 + 5;
const int LMAX = 100000 + 5;
const int VMAX = 100000 + 5;
int N, M;
vector<int> V[NMAX];
int euler[2 * NMAX], cnt;
int first[NMAX];
int lvl[NMAX];
PII RMQ[18][2 * NMAX];
void dfs(int x) {
euler[++cnt] = x;
first[x] = cnt;
for(auto y : V[x]) {
lvl[y] = lvl[x] + 1;
dfs(y);
euler[++cnt] = x;
}
}
void build() {
int i, j, p;
for(i = 1; i <= cnt; i++)
RMQ[0][i] = make_pair(lvl[euler[i]], euler[i]);
for(i = 1, p = 2; p <= cnt; i++, p <<= 1)
for(j = 1; j + p / 2 <= cnt; j++)
RMQ[i][j] = min(RMQ[i - 1][j], RMQ[i - 1][j + p / 2]);
}
int query(int x, int y) {
x = first[x];
y = first[y];
if(x > y)
swap(x, y);
int d = (y - x + 1);
int i = log2(d - 0.9);
int p = (1 << i);
return min(RMQ[i][x], RMQ[i][y - p + 1]).second;
}
int main() {
int i, x, y;
#ifndef ONLINE_JUDGE
freopen(inputFile.c_str(), "r", stdin);
freopen(outputFile.c_str(), "w", stdout);
#endif
scanf("%d%d", &N, &M);
for(i = 2; i <= N; i++) {
scanf("%d", &x);
V[x].push_back(i);
}
dfs(1);
build();
while(M--) {
scanf("%d%d", &x, &y);
printf("%d\n", query(x, y));
}
return 0;
}