Cod sursa(job #3220647)
| Utilizator | Data | 4 aprilie 2024 15:45:21 | |
|---|---|---|---|
| Problema | Lowest Common Ancestor | Scor | 90 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 0.63 kb |
#include <fstream>
#define NMAX 100000
using namespace std;
ifstream in("lca.in");
ofstream out("lca.out");
int tata[NMAX + 5], nivel[NMAX + 5];
int lca(int x, int y) {
while (x != y) {
if (nivel[x] < nivel[y])
y = tata[y];
else
x = tata[x];
}
return x;
}
int main()
{
int n, m;
in >> n >> m;
nivel[1] = 1;
for (int i = 2; i <= n; i++) {
in >> tata[i];
nivel[i] = nivel[tata[i]] + 1;
}
for (int i = 1; i <= m; i++) {
int x, y;
in >> x >> y;
out << lca(x, y) << '\n';
}
return 0;
}
