Pagini recente » Cod sursa (job #1053935) | Cod sursa (job #2663220) | Cod sursa (job #627965) | Cod sursa (job #3124245) | Cod sursa (job #2928374)
#include <iostream>
#include <fstream>
#define MAX_SIZE 100000
int rmq(const int *a, const int *sections, int q, int x, int y);
int main() {
std::ifstream input("rmq.in");
std::ofstream output("rmq.out");
int n, m, a[MAX_SIZE] = {0};
input >> n >> m;
for (int i = 0; i < n; ++i) input >> a[i];
int sections[MAX_SIZE] = {0};
int q = 1;
for (int i = 1; i * i <= n; ++i) q = i;
int bucket = 0;
for (int j = 0; j < n; ++j) {
sections[bucket] = -1;
int i;
for (i = bucket * q; i < (bucket + 1) * q && i < n; ++i) {
if (sections[bucket] == -1) sections[bucket] = i;
else {
if (a[i] < a[sections[bucket]]) sections[bucket] = i;
}
}
bucket++;
j = i - 1;
}
while (m--) {
int x, y;
input >> x >> y;
x--, y--;
int min = rmq(a, sections, q, x, y);
output << min << '\n';
}
return 0;
}
int rmq(const int *a, const int *sections, int q, int x, int y) {
int start = x / q;
int finish = y / q;
int min = INT32_MAX;
for (int i = start + 1; i <= finish - 1; ++i) {
min = std::min(min, a[sections[i]]);
}
for (int i = x; (i <= ((start + 1) * q - 1)) && i <= y; ++i) {
min = std::min(min, a[i]);
}
for (int i = std::max(finish * q, x); i <= y; ++i) {
min = std::min(min, a[i]);
}
return min;
}