Pagini recente » Cod sursa (job #1697340) | Cod sursa (job #2548769) | Cod sursa (job #2483885) | Cod sursa (job #1298042) | Cod sursa (job #1133157)
#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; }
/***
LCA with Heavy Path Decomposition
N log N / query
**/
int N, M, numPaths;
int pathWhere[MAXN], pathFather[MAXN], depth[MAXN], heavy[MAXN];
Graph G;
void DFs(int Node, int Father, int actLevel) {
heavy[Node] = 1;
depth[Node] = actLevel;
int heaviest = -1;
for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
if(*it == Father)
continue;
DFs(*it, Node, actLevel + 1);
heavy[Node] += heavy[*it];
if(heaviest == -1)
heaviest = *it;
else if(heavy[heaviest] < heavy[*it])
heaviest = *it;
}
if(heaviest == -1) {
pathWhere[Node] = ++ numPaths;
pathFather[pathWhere[Node]] = Father;
return;
}
pathWhere[Node] = pathWhere[heaviest];
pathFather[pathWhere[Node]] = Father;
}
int LCA(int x, int y) {
if(pathWhere[x] == pathWhere[y]) {
if(depth[x] > depth[y])
swap(x, y);
return x;
}
if(depth[pathFather[pathWhere[x]]] < depth[pathFather[pathWhere[y]]])
swap(x, y);
return LCA(pathFather[pathWhere[x]], y);
}
int main() {
fin >> N >> M;
for(int i = 2 ; i <= N ; ++ i) {
int x;
fin >> x;
G[x].push_back(i);
G[i].push_back(x);
}
DFs(1, 0, 1);
for(int i = 1 ; i <= M ; ++ i) {
int x, y;
fin >> x >> y;
fout << LCA(x, y) << '\n';
}
fin.close();
fout.close();
return 0;
}