Pagini recente » Cod sursa (job #2042423) | Borderou de evaluare (job #2484080) | Cod sursa (job #2772405) | Rating Afloroaie Pricop Miruna (MirunaAfloroaie) | Cod sursa (job #1796562)
#include <cstdio>
#include <cstring>
#include <algorithm>
const int MaxN=100005,MaxLog=17;
using namespace std;
FILE *IN,*OUT;
int Father[MaxLog][MaxN],h[MaxN],N,M,X,Y;
int LCA(int a,int b)
{
if(h[a]<h[b])
swap(a,b);
if(h[a]>h[b])
{
int i=MaxLog-1;
while(i>=0)
{
if(h[Father[i][a]]>=h[b])
a=Father[i][a];
i--;
}
}
if(a==b)return a;
else
{
int i=MaxLog-1;
while(i>=0)
{
if(Father[i][a]!=Father[i][b])
a=Father[i][a],b=Father[i][b];
i--;
}
}
return Father[0][a];
}
int main()
{
IN=fopen("lca.in","r");
OUT=fopen("lca.out","w");
fscanf(IN,"%d %d ",&N,&M);
Father[0][1]=-1;
h[1]=1;
for(int i=2;i<=N;i++)
{
fscanf(IN,"%d ",&Father[0][i]);
h[i]=1+h[Father[0][i]];
}
for(int i=1;i<=N;i++)
{
for(int j=1;j<MaxLog;j++)
Father[j][i]=Father[j-1][Father[j-1][i]];
}
for(int i=1;i<=M;i++)
{
fscanf(IN,"%d %d ",&X,&Y);
fprintf(OUT,"%d\n",LCA(X,Y));
}
return 0;
}