Pagini recente » Cod sursa (job #2602542) | Cod sursa (job #2963446) | Cod sursa (job #3167304) | Cod sursa (job #1039251) | Cod sursa (job #2509178)
#include <bits/stdc++.h>
using namespace std;
//varianta 2 - Heavy Path
ifstream f("lca.in");
ofstream g("lca.out");
const int nmax = 100005;
vector <int> son[nmax];
int deep[nmax];
int weight[nmax];
int where[nmax];
int last[nmax];
int father[nmax];
int cnt;
void dfs(int nod, int lvl)
{
deep[nod] = lvl;
int maxSon = 0;
for (auto el : son[nod])
{
dfs(el, lvl + 1);
weight[nod] += weight[el] + 1;
if (maxSon == 0 || weight[el] > weight[maxSon])
maxSon = el;
}
if (weight[nod] == 0)
{
where[nod] = ++ cnt;
last[cnt] = nod;
}
else
{
assert(maxSon != 0);
where[nod] = where[maxSon];
last[where[nod]] = nod;
}
}
int solve(int a, int b)
{
while (where[a] != where[b])
{
if (deep[last[where[a]]] < deep[last[where[b]]])
swap(a, b);
a = father[last[where[a]]];
}
if (weight[a] > weight[b])
return a;
else
return b;
}
int main()
{
int n, m;
f >> n >> m;
for (int i = 1; i < n; ++ i)
{
int x;
f >> x;
son[x].push_back(i + 1);
father[i + 1] = x;
}
dfs(1, 1);
for (int i = 1; i <= m; ++ i)
{
int a, b;
f >> a >> b;
g << solve(a, b) << '\n';
}
}