Cod sursa(job #533732)

Utilizator andra23Laura Draghici andra23 Data 14 februarie 2011 15:31:46
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include<fstream>
#include<cmath>
#define maxn 100005
#define maxm 1000005

using namespace std;

int n, m;
int a[maxn], v[maxn];

int main() {
    ifstream f("rmq.in");
    ofstream g("rmq.out");
    
    f >> n >> m;
    int i, j;
    int x, y;
    
    for (i = 1; i <= n; i++)
        f >> a[i];
        
    int s = sqrt(n);
    for (i = 1; i <= n; i = i+s) {
        x = a[i];
        for (j = i+1; j < i+s && j <= n; j++) {
            if (a[j] < x)
                x = a[j];
        }
        v[i/s] = x;
    }
    
    for (i = 1; i <= m; i++) {
        f >> x >> y;
        int ai = x/s;
        int b = y/s;
        int minim = a[x];
        
        for ( j = ai+1; j <= b-1; j++)
            if (minim > v[j]) 
                minim = v[j];
        
        for (j = x+1; j < (ai+1)*s; j++)
            if (minim > a[j]) 
                minim = a[j];
                
        for (j = b*s; j <= y; j++)
            if (minim > a[j]) 
                minim = a[j];
            
        g << minim << '\n';
    }
}