Cod sursa(job #1679697)

Utilizator TarabanDragosTaraban Dragos-Petru TarabanDragos Data 8 aprilie 2016 10:18:52
Problema Lowest Common Ancestor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include<cstdio>
#include<vector>
using namespace std;
vector<int>L[200100];
int n,m,a,b,c,d,i,j,nr,v[200100],x[20][200100],y[200100],t[200100],p[200100];
FILE *f,*g;
void dfs(int nod,int niv){
    x[0][ ++ nr ] = nod;
    y[nod] = niv;
    if( !v[nod] )
        v[nod] = nr;
    for(int i=0;i<L[nod].size();i++){
        dfs( L[nod][i] , niv + 1 );
        x[0][ ++ nr ] = nod;
    }
}
int main(){
    f=fopen("lca.in","r");
    g=fopen("lca.out","w");
    fscanf(f,"%d%d",&n,&m);
    for(i=2;i<=n;i++){
        fscanf(f,"%d",&t[i]);
        L[ t[i] ].push_back(i);
    }
    for(i=1;i<=200000;i++){
        p[i] = p[ i / 2 ] + 1;
    }
    dfs( 1 , 1 );
    for(i=1;i<=p[n];i++){
        a = 1 << ( i - 1 );
        for(j=1;j<=nr;j++){
            if( a + j <= nr ){
                if( y[ x[ i - 1 ][j] ] < y[ x[ i - 1 ][ a + j ] ] )
                    x[i][j] = x[ i - 1 ][j];
                else
                    x[i][j] = x[ i - 1 ][ a + j ];
            }
            else
                x[i][j] = x[ i - 1 ][j];
        }
    }
    for(i=1;i<=m;i++){
        fscanf(f,"%d%d",&a,&b);
        a = v[a];
        b = v[b];
        if( a > b ){
            int aux = a;
            a = b;
            b = aux;
        }
        c = b - a + 1;
        d = 1 << ( p[c] - 1 );
        if( y[ x[ p[c] - 1 ][a] ] < y[ x[ p[c] - 1 ][ b - d + 1 ] ] )
            fprintf(g,"%d\n",x[ p[c] - 1 ][a]);
        else
            fprintf(g,"%d\n",x[ p[c] - 1 ][ b - d +1 ]);
    }

    fclose(f);
    fclose(g);
    return 0;
}