Pagini recente » Cod sursa (job #3037323) | Cod sursa (job #1549150) | Cod sursa (job #612572) | Cod sursa (job #1113210) | Cod sursa (job #2626887)
#include <fstream>
#include <cstring>
using namespace std;
ifstream f ("lca.in");
ofstream g ("lca.out");
int n, q;
int tata[100005];
bool used[100005];
int Lca (int nod1, int nod2)
{
while (nod1)
{
used[nod1] = 1;
nod1 = tata[nod1];
}
while (nod2)
{
if (used[nod2])
return nod2;
if (used[tata[nod2]])
return tata[nod2];
nod2 = tata[nod2];
}
}
int main()
{
f >> n >> q;
for (int i=2; i<=n; i++)
f >> tata[i];
while (q -- )
{
int nod1, nod2;
f >> nod1 >> nod2;
memset(used, 0, sizeof(used));
g << Lca(nod1, nod2) << "\n";
}
return 0;
}