Pagini recente » Cod sursa (job #1816585) | Cod sursa (job #1181075) | Cod sursa (job #187690) | Cod sursa (job #2534759) | Cod sursa (job #2358330)
#include <bits/stdc++.h>
#define nmax 100001
using namespace std;
ofstream fout("lca.out");
ifstream fin("lca.in");
int n,m,ancestor;
vector <int> L[nmax];
bitset <nmax> viz;
void BFS(int x, int y)
{
int nod;
queue <int> q;
viz.reset();
q.push(x);
q.push(y);
viz[x] = viz[y] = 1;
while(!q.empty())
{
nod = q.front();
q.pop();
for(auto i : L[nod])
if(viz[i] == 0)
{
viz[i] = 1;
q.push(i);
}
else
{
ancestor = i;
}
}
}
int main()
{
int x,y;
fin >> n >> m;
y = 2;
n--;
while(n--)
{
fin >> x;
L[y].push_back(x);
y++;
}
while(m--)
{
fin >> x >> y;
BFS(x,y);
fout << ancestor << "\n";
}
fin.close();
fout.close();
return 0;
}