Cod sursa(job #2973323)
| Utilizator | Data | 31 ianuarie 2023 18:56:38 | |
|---|---|---|---|
| Problema | Lowest Common Ancestor | Scor | 90 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 0.54 kb |
#include <bits/stdc++.h>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int main()
{
int n, m;
fin >> n >> m;
vector<int> asc(n + 1), row(n + 1);
row[1] = 1;
for (int i = 2; i <= n; i++)
fin >> asc[i], row[i] = row[asc[i]] + 1;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
if (row[x] < row[y])
swap(x, y);
while (row[x] > row[y])
x = asc[x];
while (x != y)
x = asc[x], y = asc[y];
fout << x << "\n";
}
return 0;
}