Pagini recente » Cod sursa (job #2947916) | Cod sursa (job #2062149) | Cod sursa (job #2500513) | Cod sursa (job #835033) | Cod sursa (job #2252718)
#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;
}
int queryChunkSize(int left, int right) {
return (int) 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; i <= log2(n); i++) {
for(int j = 0; j < n - pow(2, i-1); j++) {
int shift = (int) pow(2, 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 = (int) pow(2, 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;
}