Pagini recente » Cod sursa (job #906402) | Cod sursa (job #923799) | Cod sursa (job #1388568) | Cod sursa (job #2417459) | Cod sursa (job #2973325)
#include <vector>
#include <fstream>
using namespace std;
ifstream fin("lca.in");
ofstream fout("lca.out");
int main()
{
ios::sync_with_stdio(false);
fin.tie(NULL);
fout.tie(NULL);
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;
}