Pagini recente » Cod sursa (job #357625) | Cod sursa (job #3292302) | Cod sursa (job #1054877) | Cod sursa (job #651730) | Cod sursa (job #2970841)
/*
* O(Q * N)
*/
#include <fstream>
#include <vector>
using namespace std;
const int MAX_N = 100005;
int N, Q;
vector<int> arbore[MAX_N];
int parinte[MAX_N], nivel[MAX_N];
void dfs(int nod, int nvl = 1)
{
nivel[nod] = nvl;
for (int fiu : arbore[nod])
{
dfs(fiu, nvl + 1);
}
}
int lca(int x, int y)
{
if (nivel[x] < nivel[y])
{
swap(x, y);
}
while (nivel[x] > nivel[y])
{
x = parinte[x];
}
while (x != y)
{
x = parinte[x];
y = parinte[y];
}
return x;
}
int main()
{
ifstream fin("lca.in");
ofstream fout("lca.out");
fin >> N >> Q;
for (int nod = 2; nod <= N; ++nod)
{
fin >> parinte[nod];
arbore[parinte[nod]].push_back(nod);
}
dfs(1);
while (Q--)
{
int x, y;
fin >> x >> y;
fout << lca(x, y) << "\n";
}
return 0;
}