Pagini recente » Cod sursa (job #3124973) | Cod sursa (job #3172658) | Diferente pentru implica-te/arhiva-educationala intre reviziile 22 si 223 | Cod sursa (job #3123470) | Cod sursa (job #1700782)
#include <fstream>
#include <vector>
using namespace std;
const int N = 1 + 1e5;
int head[N], start[N], stop[N], timp, n;
vector<int> sons[N];
void mark(int x, int H){
head[x] = H;
for (int y : sons[x])
if ( !head[y] )
mark(y, H);
}
int dfs(int x){
start[x] = ++timp;
int weight = 1, best = -1, son;
for (int y : sons[x]){
int val = dfs(y);
weight += val;
if ( best < val ){
best = val;
son = y;
}
}
for (int y : sons[x])
if ( y != son )
mark(y, x);
stop[x] = ++timp;
return weight;
}
inline int isAncestor(int T, int x){
return start[T] <= start[x] && stop[x] <= stop[T];
}
int lca(int a, int b){
int x = a, y = b;
while (!isAncestor(x, b))
x = head[x];
while (!isAncestor(y, a))
y = head[y];
return isAncestor(y, x) ? x : y;
}
inline void prepare(int root){
dfs(root); mark(root, root);
}
int main(){
ifstream in("lca.in");
ofstream out("lca.out");
int nrQ, x, y;
in >> n >> nrQ;
for (int i = 2 ; i <= n ; i++){
in >> x;
sons[x].push_back(i);
}
prepare(1);
while (nrQ--){
in >> x >> y;
out << lca(x, y) << '\n';
}
return 0;
}