Cod sursa(job #1149309)

Utilizator BlueStrutAndrei Prahoveanu BlueStrut Data 21 martie 2014 17:38:14
Problema Range minimum query Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include<cstdio>
using namespace std;
int min(int a, int b){if (a<=b) return a; else return b;}
int i, n, x, y, k, j, p, a[19][100001], mn;
int det(int n){
    int d=0;
    while (n>1) {n=n>>1; d++;}
    return d;
}
int main(){
    freopen("rmq.in","r",stdin);
    freopen("rmq.out","w",stdout);
    scanf("%d%d", &n, &k);
    for (i=1;i<=n;i++) scanf("%d", &a[1][i]); p=1;
    for (i=2;p<=n;i++) {
        for (j=1;j+p<=n;j++) {
            a[i][j]=min(a[i-1][j], a[i-1][j+p]);
        }
        p=p<<1;
    }
    for (i=1;i<=k;i++) {
        scanf("%d%d", &x, &y); p=det(y-x+1);
        mn=999999999;
        p=det(y-x+1);
        while (x+p<=y) {
            mn=min(a[p+1][x], mn);
            x+=(1<<p);
        }
        x=y-(1<<p)+1;
        mn=min(a[p+1][x], mn);
        printf("%d\n", mn);
    }
    return 0;
}