Pagini recente » Cod sursa (job #1491241) | Cod sursa (job #434961) | Cod sursa (job #438344) | Cod sursa (job #1905715) | Cod sursa (job #1116588)
#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 MAXL = 22;
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; }
template<class T, const int MAXN, const int MAXLG, const int A[]>
class RMQ {
T rmq[MAXLG][MAXN];
T Log[MAXN];
public:
inline void BuildLog(const int &N) {
for(int i = 2 ; i <= N ; ++ i)
Log[i] = Log[i >> 1] + 1;
}
inline void BuildRMQ(const int &N) {
for(int i = 1 ; i <= N ; ++ i)
rmq[0][i] = i;
for(int i = 1 ; (1 << i) <= N ; ++ i)
for(int j = 1 ; j + (1 << i) - 1 <= N ; ++ j) {
rmq[i][j] = rmq[i - 1][j];
int l = (1 << (i - 1));
if(A[rmq[i][j]] > A[rmq[i - 1][j + l]])
rmq[i][j] = rmq[i - 1][j + l];
}
}
inline int Query(int X, int Y) {
int lg = Log[Y - X + 1];
int Ans = rmq[lg][X];
if(A[Ans] > A[rmq[lg][Y - (1 << lg) + 1]])
Ans = rmq[lg][Y - (1 << lg) + 1];
return Ans;
}
};
Graph G;
int N, M, K, Level[MAXN << 1], First[MAXN], Euler[MAXN << 1];
RMQ <int, MAXN << 1, MAXL, Level> range;
void DFs(int Node, int Father, int actLevel) {
Euler[++ K] = Node;
First[Node] = K;
Level[K] = actLevel;
for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
if(*it == Father)
continue;
DFs(*it, Node, actLevel + 1);
Euler[++ K] = Node;
Level[K] = actLevel;
}
}
int main() {
fin >> N >> M;
for(int i = 2 ; i <= N ; ++ i) {
int x;
fin >> x;
G[x].push_back(i);
}
DFs(1, 1, 1);
range.BuildLog(K);
range.BuildRMQ(K);
for(int i = 1 ; i <= M ; ++ i) {
int x, y;
fin >> x >> y;
x = First[x];
y = First[y];
if(x > y)
swap(x, y);
fout << Euler[range.Query(x, y)] << '\n';
}
fin.close();
fout.close();
return 0;
}