Cod sursa(job #1796602)

Utilizator nnnmmmcioltan alex nnnmmm Data 3 noiembrie 2016 17:03:01
Problema Lowest Common Ancestor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include<cstdio>
#include<algorithm>

const int NMAX=100001,PMAX=17;

int str[PMAX][NMAX],h[NMAX];
///str[i][j] = al 2^i-lea stramos al lui j

int lca(int x,int y)
{
 if(h[x]<h[y])
    {
     int aux=x;
     x=y;
     y=aux;
     //std::swap(x,y);
    }
 if(h[x]>h[y])
    {
     int i=PMAX-1;
     while(i>=0)
           {
            if(h[str[i][x]]>=h[y])
               x=str[i][x];
            i--;
           }
    }
 if(x==y)
    return x;
 else
    {
     int i=PMAX-1;
     while(i>=0)
           {
            if(str[i][x]!=str[i][y])
               x=str[i][x],y=str[i][y];
            i--;
           }
    }
 return str[0][x];
}

int main()
{
 FILE *in=fopen("lca.in","r");
 int n,m;
 fscanf(in,"%d %d ",&n,&m);
 h[1]=1;
 str[0][1]=-1;
 for(int i=2;i<=n;i++)
     {
      fscanf(in,"%d ",&str[0][i]);
      h[i]=h[str[0][i]]+1;
     }
for(int i=1;i<PMAX;i++)
    for(int j=1;j<=n;j++)
        {
         str[i][j]=str[i-1][str[i-1][j]];
        }
 FILE *out=fopen("lca.out","w");
 for(int q=1;q<=m;q++)
     {
      int a,b;
      fscanf(in,"%d %d ",&a,&b);
      fprintf(out,"%d\n",lca(a,b));
     }
 fclose(in);
 fclose(out);
 return 0;
}