Pagini recente » Cod sursa (job #1973930) | Cod sursa (job #859281) | Cod sursa (job #1210924) | Cod sursa (job #2777827) | Cod sursa (job #2086406)
#include <fstream>
#include <vector>
using namespace std;
const int h = 200;
int N, M, tata[100010], interval[100010], nivel[100010];
vector <int> G[100010];
void dfs(int nod, int n1, int lev)
{
nivel[nod] = lev;
interval[nod] = n1;
if(lev % h == 0) {
n1 = nod;
}
for (vector<int>::iterator it = G[nod].begin(); it != G[nod].end(); ++it) {
dfs(*it, n1, lev + 1);
}
}
int lca(int x, int y)
{
while(interval[x] != interval[y]) {
if(nivel[x] > nivel[y])
x = interval[x];
else
y = interval[y];
}
while(x != y) {
if(nivel[x] > nivel[y])
x = tata[x];
else
y = tata[y];
}
return x;
}
int main()
{
ifstream in ("lca.in");
ofstream out ("lca.out");
in >> N >> M;
for(int i = 2; i <= N; ++i) {
in >> tata[i];
G[tata[i]].push_back(i);
}
dfs(1, 0, 0);
while(M--) {
int x, y;
in >> x >> y;
out << lca(x, y) << "\n";
}
}