Pagini recente » Borderou de evaluare (job #2661758) | Cod sursa (job #1988370) | Borderou de evaluare (job #2015145) | Borderou de evaluare (job #2018422) | Cod sursa (job #2509023)
#include <bits/stdc++.h>
using namespace std;
//varianta 1 - brute force
const int nmax = 100005;
int deep[nmax];
int father[nmax];
vector <int> son[nmax];
ifstream f("lca.in");
ofstream g("lca.out");
void dfs(int nod, int lvl)
{
deep[nod] = lvl;
for (auto el : son[nod])
dfs(el, lvl + 1);
}
int main()
{
int n, m;
f >> n >> m;
for (int i = 1; i < n; ++ i)
{
int nod;
f >> nod;
son[nod].push_back(i + 1);
father[i + 1] = nod;
}
dfs(1, 1);
while (m --)
{
int a, b;
f >> a >> b;
while (a != b)
{
if (deep[a] > deep[b])
a = father[a];
else
b = father[b];
}
g << a << '\n';
}
}