Cod sursa(job #1493326)
Utilizator | Data | 29 septembrie 2015 00:03:40 | |
---|---|---|---|
Problema | Lowest Common Ancestor | Scor | 40 |
Compilator | c | Status | done |
Runda | Arhiva educationala | Marime | 0.59 kb |
#include <stdio.h>
#include <stdlib.h>
int t[100000], niv[100000], n, m, x, y, i, a1, a2, aux;
int main()
{
freopen("lca.in", "r", stdin);
freopen("lca.out", "w", stdout);
scanf("%d %d", &n, &m);
niv[1] = 0;
for (i = 2; i <= n; i++)
{
scanf("%d", &t[i]);
niv[i] = niv[t[i]] + 1;
}
for (i = 0; i < m; i++)
{
scanf("%d %d", &x, &y);
if(niv[x] < niv[y])
{
aux = x;
x = y;
y = aux;
}
while(niv[x] > niv[y])
{
x = t[x];
}
while(x != y)
{
x = t[x];
y = t[y];
}
printf("%d\n", x);
}
return 0;
}