Cod sursa(job #2252764)

Utilizator AngelEclipseGarleanu Alexandru Stefan AngelEclipse Data 3 octombrie 2018 00:07:52
Problema Range minimum query Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("rmq.in");
ofstream g("rmq.out");
int lookup[100001][17];

/* unsigned long pow(unsigned long base, unsigned long exponent) {
    unsigned long sol = 1;
    for(int i = 1; i<(1<<30); i = i*2) {
        if(i&exponent) sol = sol * base;
        base *= base;
    }
    return sol;
} */

void adaptInfoarenaInput(int& a, int& b) {
    a--;
    b--;
}

void preprocess(int n) {
    for(int i = 0; i < n; i++) {
        f>>lookup[i][0];
    }
    for(int i = 1; (1<<i) <= n; i++) {
        for(int j = 0; j < n - (1<<(i-1)); j++) {
            int shift = (1<<(i-1));
            lookup[j][i] = min(lookup[j][i - 1], lookup[j+shift][i-1]);
//            cout<<"formed lookup["<<i<<"]["<<j<<"] from lookup["<<i-1<<"]["<<j<<"] and lookup["<<i-1<<"]["<<j + shift<<"]\n";
        }
    }
}

int rangeMinimumQuery(int left, int right) {
//    cout<<"Start query"<<left<<" "<<right<<'\n';
    int chunkSize = floor(log2(right - left + 1));
//    cout<<"Chunk size is "<<chunkSize<<'\n';
    int shift = 1 << chunkSize;
//    cout<<"Shift is "<<shift<<'\n';
//    cout<<"calculating min of lookup["<<chunkSize<<"]["<<left<<"] and lookup["<<chunkSize<<"]["<<right - shift + 1<<"]\n";
    return min(lookup[left][chunkSize], lookup[right - shift + 1][chunkSize]);
}


int main() {
    int n, m;
    f>>n>>m;
    preprocess(n);

    int tempLeft, tempRight;
    for(int i = 0; i < m; i++) {
        f>>tempLeft>>tempRight;
        adaptInfoarenaInput(tempLeft, tempRight);
        g<<rangeMinimumQuery(tempLeft, tempRight)<<'\n';
    }

/*     cout<<'\n';
    for(int i = 0; i <= log2(n); i++) {
        for(int j = 0; j < n - pow(2, i-1); j++) {
            cout<<lookup[i][j]<<" ";
        }
        cout<<'\n';
    } */

    f.close();
    g.close();
    return 0;
}