Pagini recente » Cod sursa (job #2951775) | Cod sursa (job #2894547) | Cod sursa (job #170150) | Cod sursa (job #1386731) | Cod sursa (job #1238686)
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <deque>
using namespace std;
const char infile[] = "lca.in";
const char outfile[] = "lca.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 100005;
const int oo = 0x3f3f3f3f;
typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
Graph g;
int n, m, k, euler[MAXN << 1], first[MAXN], level[MAXN << 1], rmq[20][MAXN << 1], Log[MAXN << 1];
inline void dfs(int node, int actlevel) {
first[node] = ++ k;
euler[k] = node;
level[k] = actlevel;
for(It it = g[node].begin(), fin = g[node].end(); it != fin ; ++ it) {
dfs(*it, actlevel + 1);
euler[++k] = node;
level[k] = actlevel;
}
}
inline void buildrmq() {
for(int i = 2 ; i <= k ; ++ i)
Log[i] = Log[i >> 1] + 1;
for(int i = 1 ; i <= k ; ++ i)
rmq[0][i] = i;
for(int i = 1 ; (1 << i) <= k ; ++ i) {
int aux = (1 << (i - 1));
for(int j = 1 ; j + (1 << i) - 1 <= k ; ++ j) {
rmq[i][j] = rmq[i - 1][j];
if(level[rmq[i][j]] > level[rmq[i - 1][j + aux]])
rmq[i][j] = rmq[i - 1][j + aux];
}
}
}
inline int query(int x, int y) {
x = first[x];
y = first[y];
if(x > y)
swap(x, y);
int lg = Log[y - x + 1];
int ans = rmq[lg][x];
if(level[ans] > level[rmq[lg][y - (1 << lg) + 1]])
ans = rmq[lg][y - (1 << lg) + 1];
return euler[ans];
}
int main() {
fin >> n >> m;
for(int i = 2 ; i <= n ; ++ i) {
int x;
fin >> x;
g[x].push_back(i);
}
dfs(1, 1);
buildrmq();
while(m -- ) {
int x, y;
fin >> x >> y;
fout << query(x, y) << '\n';
}
fin.close();
fout.close();
return 0;
}