Cod sursa(job #275300)

Utilizator raula_sanChis Raoul raula_san Data 10 martie 2009 12:59:50
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <cstdio>

#define MAX_N 100001
#define LOG_N 18

int A[MAX_N], R[LOG_N][MAX_N];
int N, M;

void Process()
{
     int i;
     for ( i = 1; i <= N; ++i )
         R[0][i] = A[i];

     int j, x, y;
     for ( i = 1; (1 << i) <= N; ++i )
         for ( j = 1; j <= N; ++j )
         {
             x = R[i-1][j];
             y = 0x3f3f3f3f;
             
             if(j + (1 << (i-1)) <= N)
               y = R[i-1][j+(1<<(i-1))];
             
             x = x < y ? x : y;
             
             R[i][j] = x;
             
//           printf("L:%d S:%d -> %d\n", (1<<i), j, R[i][j]);
         }
}

int main()
{
    freopen("rmq.in", "rt", stdin);
    freopen("rmq.out", "wt", stdout);
    
    int i;
    for ( scanf("%d %d", &N, &M), i = 1; i <= N; ++i )
        scanf("%d", A+i);
    
    Process();

    int a, b;
    for ( i = 1; i <= M; ++i )
    {
        scanf("%d %d", &a, &b);
        int l = b - a + 1;
        int j, x, y;
        
        for ( j = 0; (1 << j) <= l; ++j ); -- j;
        x = R[j][a];
        y = R[j][b-(1<<j)+1];
        
        printf("%d\n", x<y?x:y);
    }
    
    fclose(stdin);
    fclose(stdout);
    return 0;
}