Cod sursa(job #1818049)

Utilizator alittlezzCazaciuc Valentin alittlezz Data 28 noiembrie 2016 19:37:23
Problema Range minimum query Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <cstdio>
#include <algorithm>
#include <ctype.h>

using namespace std;

class InParser {
private:
    FILE *fin;
    char *buff;
    int sp;

    char read_ch() {
        ++sp;
        if (sp == 4096) {
            sp = 0;
            fread(buff, 1, 4096, fin);
        }
        return buff[sp];
    }

public:
    InParser(const char* nume) {
        fin = fopen(nume, "r");
        buff = new char[4096]();
        sp = 4095;
    }

    InParser& operator >> (int &n) {
        char c;
        while (!isdigit(c = read_ch()) && c != '-');
        int sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }

    InParser& operator >> (long long &n) {
        char c;
        n = 0;
        while (!isdigit(c = read_ch()) && c != '-');
        long long sgn = 1;
        if (c == '-') {
            n = 0;
            sgn = -1;
        } else {
            n = c - '0';
        }
        while (isdigit(c = read_ch())) {
            n = 10 * n + c - '0';
        }
        n *= sgn;
        return *this;
    }
};

int rmq[17][100005];
int lg2[100005];
int pow2[17];

int main() {
    int i,j,n,q,limit,lf,rg;
    InParser fin("home.in");
    freopen("home.out", "w", stdout);
    fin>>n>>q;
    lg2[2] = 1;
    for(i = 3;i <= n;i++){
        lg2[i] = lg2[i>>1] + 1;
    }
    pow2[0] = 1;
    for(i = 1;i <= lg2[n];i++){
        pow2[i] = pow2[i-1]<<1;
    }
    for(i = 1;i <= n;i++){
        fin>>rmq[0][i];
    }
    for(j = 1;j <= lg2[n];j++){
        limit = n - ((1<<j) - 1);
        for(i = 1;i <= limit;i++){
            rmq[j][i] = min(rmq[j-1][i], rmq[j-1][i + pow2[j-1]]);
        }
    }
    for(i = 1;i <= q;i++){
        fin>>lf>>rg;
        limit = lg2[rg - lf + 1];
        printf("%d\n", min(rmq[limit][lf], rmq[limit][rg - pow2[limit] + 1]));
    }
    return 0;
}