Cod sursa(job #2252760)

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

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

/* 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;
} */


int queryChunkSize(int left, int right) {
    return (int) floor(log2(right - left + 1));
}

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

void preprocess(int n) {
    for(int i = 0; i < n; i++) {
        f>>lookup[0][i];
    }
    for(int i = 1; (1<<i) <= n; i++) {
        for(int j = 0; j < n - (1<<i-1); j++) {
            int shift = (1<<i-1);
            lookup[i][j] = min(lookup[i-1][j], lookup[i-1][j+shift]);
//            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 = queryChunkSize(left, right);
//    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[chunkSize][left], lookup[chunkSize][right - shift + 1]);
}


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;
}