Pagini recente » Cod sursa (job #2943734) | Cod sursa (job #741417) | Cod sursa (job #1818038) | Cod sursa (job #1052008) | Cod sursa (job #2306824)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
const int NMAX = 100005;
vector<int> g[NMAX], p[NMAX];
int color[NMAX], ncolors;
int dad[NMAX], h[NMAX];
int dfs(int node, int level) {
int mx = 0, son, dim = 1;
for(auto it: g[node])
if(h[it] == 0) {
h[it] = h[node] + 1;
dad[it] = node;
int aux = dfs(it, level + 1);
if(aux > mx) {
mx = aux;
son = it;
}
dim += aux;
}
if(dim == 1) {
ncolors ++;
color[node] = ncolors;
p[ncolors].push_back(node);
} else {
color[node] = color[son];
p[color[son]].push_back(node);
}
return dim;
}
int main() {
int n, m;
in >> n >> m;
for(int i = 2; i <= n; i ++) {
int x;
in >> x;
g[x].push_back(i);
g[i].push_back(x);
}
h[1] = 1;
dfs(1, 1);
for(int qr = 1; qr <= m; qr ++) {
int x, y;
in >> x >> y;
while(color[x] != color[y]) {
int fatherx = p[color[x]].back(), fathery = p[color[y]].back();
if(h[fatherx] > h[fathery]) {
x = fatherx;
x = dad[x];
} else {
y = fathery;
y = dad[y];
}
}
if(h[x] < h[y])
out << x << "\n";
else
out << y << "\n";
}
return 0;
}