Pagini recente » Cod sursa (job #2510216) | Cod sursa (job #1916736) | Cod sursa (job #1057254) | Cod sursa (job #664766) | Cod sursa (job #2864430)
#include<bits/stdc++.h>
using namespace std;
FILE *f=fopen("lca.in","r");
FILE *g=fopen("lca.out","w");
const int NMAX = 100004;
int N,M,Tata[NMAX],Nivel[NMAX],Rad=1;
vector<int>G[NMAX]; /// lista de adiacenta a grafului
bitset<NMAX>viz;
void Read()
{
fscanf(f,"%d%d",&N,&M);
for(int i=2; i<=N; i++)
{
fscanf(f,"%d",&Tata[i]);
G[i].push_back(Tata[i]);
G[Tata[i]].push_back(i);
}
}
void Dfs(int nodCurent,int nivel)
{
viz[nodCurent]=true;
Nivel[nodCurent]=nivel;
for(int nodVecin:G[nodCurent])
if(!viz[nodVecin])Dfs(nodVecin,nivel+1);
}
int LCA(int x,int y)
{
while(1)
{
if(x==y)return x;
if(Tata[x]==y)return y;
if(Tata[y]==x)return x;
if(Tata[x]==Tata[y])return Tata[x];
if(Nivel[x]==Nivel[y])
x=Tata[x],y=Tata[y];
else if(Nivel[x]>Nivel[y])
x=Tata[x];
else y=Tata[y];
}
}
void Solve()
{
Dfs(Rad,0);
for(int m=1;m<=M;m++)
{
int x,y;fscanf(f,"%d%d",&x,&y);
fprintf(g,"%d\n",LCA(x,y));
}
}
int main()
{
Read();
Solve();
fclose(f);
fclose(g);
return 0;
}