Pagini recente » Cod sursa (job #3278215) | Cod sursa (job #3205357) | Cod sursa (job #2916473) | Cod sursa (job #2975227) | Cod sursa (job #2973328)
#include <vector>
#include <fstream>
using namespace std;
FILE *fin, *fout;
int main()
{
ios::sync_with_stdio(false);
fin = fopen("lca.in", "r");
fout = fopen("lca.out", "w");
int n, m;
fscanf(fin, "%d %d", &n, &m);
vector<int> asc(n + 1), row(n + 1);
row[1] = 1;
for (int i = 2; i <= n; i++)
{
fscanf(fin, "%d", &asc[i]);
row[i] = row[asc[i]] + 1;
}
for (int i = 1; i <= m; i++)
{
int x, y;
fscanf(fin, "%d %d", &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];
fprintf(fout, "%d\n", x);
}
return 0;
}