Pagini recente » Cod sursa (job #1124671) | Cod sursa (job #2199320) | Cod sursa (job #3181731) | Cod sursa (job #1591190) | Cod sursa (job #2078022)
#include <fstream>
using namespace std;
#define LMAX 18
int main()
{
ifstream fin("rmq.in");
ofstream fout("rmq.out");
long int l, diff, sh;
long int n, m, x, y;
long int *rmq[LMAX];
long int *lg;
long int *array;
// Read the length and initialize data
fin >> n >> m;
for (int i = 0; i < LMAX; ++i) {
rmq[i] = new long int[n + 1];
}
lg = new long int [n + 1];
array = new long int[n + 1];
// Read the numbers from the array
for (int i = 1; i <= n; ++i) {
fin >> array[i];
}
// Precalculate the values for log
lg[1] = 0;
for (int i = 2; i <= n; ++i) {
lg[i] = lg[i / 2] + 1;
}
// Set the first line from RMQ sparse matrix with the elements
for (int i = 1; i <= n; ++i) {
rmq[0][i] = array[i];
}
// Divide the big interval in intervals of length 2^i
for (int i = 1; (1 << i) <= n; ++i) {
for (int j = 1; j <= n - (1 << i) + 1; ++j) {
l = 1 << (i - 1);
rmq[i][j] = rmq[i - 1][j] < rmq[i - 1][j + l] ?
rmq[i - 1][j] : rmq[i - 1][j + l];
}
}
// Read the querries and answer them
for (int i = 1; i <= m; ++i) {
fin >> x >> y;
diff = y - x + 1;
l = lg[diff];
sh = diff - (1 << l);
rmq[l][x] < rmq[l][x + sh] ? fout << rmq[l][x] << "\n" :
fout << rmq[l][x + sh] << "\n";
}
delete[] array;
delete[] lg;
for (int i = 0; i < LMAX; ++i) {
delete[] rmq[i];
}
fin.close();
fout.close();
return 0;
}