Pagini recente » Cod sursa (job #2505320) | Cod sursa (job #411990) | Cod sursa (job #2182624) | Cod sursa (job #1182786)
#include <fstream>
#include <vector>
using namespace std;
const int N = 1 + 1e5;
int T[N], son[N], head[N], depth[N], heavyDepth[N], n;
int start[N], stop[N], timp;
vector<int> tree[N];
int dfs(int x){
start[x] = ++timp;
int weight = 0, best = -1, val;
for (auto it = tree[x].begin() ; it != tree[x].end() ; it++){
depth[*it] = 1 + depth[x];
val = dfs(*it);
weight += val;
if (best < val){
best = val;
son[x] = *it;
}
}
stop[x] = ++timp;
return weight;
}
void build(int x, int H, int D){
heavyDepth[x] = D;
head[x] = H;
for (auto it = tree[x].begin() ; it != tree[x].end() ; it++)
if ( son[x] != *it )
build( *it, x, D + 1 );
else
build( *it, H, D );
}
inline int getNext(int x){
return head[x] != x ? head[x] : head[ T[x] ];
}
inline int isAncestor(int T, int x){
return start[T] <= start[x] && stop[x] <= stop[T];
}
int lca(int x, int y){
if ( isAncestor(x, y) )
return x;
if ( isAncestor(y, x) )
return y;
return lca(head[x], head[y]);
/*
while ( !isAncestor(x, y) && !isAncestor(y, x) ){
x = head[x];
y = head[y];
}
return isAncestor(x, y) ? x : y;
*/
}
int main(){
int nrQ, x, y;
ifstream in("lca.in");
in >> n >> nrQ;
for (int i = 2 ; i <= n ; i++){
in >> T[i];
tree[ T[i] ].push_back(i);
}
dfs(1);
build(1, 0, 1);
ofstream out("lca.out");
while (nrQ--){
in >> x >> y;
out << lca(x, y) << '\n';
}
in.close();
out.close();
return 0;
}