Pagini recente » Cod sursa (job #831979) | Cod sursa (job #1238668) | Cod sursa (job #2314755) | Cod sursa (job #493156) | Cod sursa (job #2923028)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <deque>
#include <queue>
#include <stack>
using namespace std;
ifstream fin("rmq.in");
ofstream fout("rmq.out");
typedef long long ll;
//table[i][j]=the position of the minimum element in the elements vector starting from position i
//and containing the next 2^j elements including i
vector<vector<int>> computeSparseTable(vector<ll>& elements) {
int n = elements.size();
vector<vector<int>> table;
table.assign(n, vector<int>(log2(n) + 1, 0));
for (int i = 0; i < n; ++i) {
table[i][0] = i;
}
for (int j = 1; (1 << j) <= n; ++j) {
for (int i = 0; i + (1 << j) - 1 < n; ++i) {
int pos1 = table[i][j - 1], pos2 = table[i + (1 << (j - 1))][j - 1];
table[i][j] = elements[pos1] < elements[pos2] ? pos1 : pos2;
}
}
// for (int j = 0; (1 << j) <= n; ++j) {
// for (int i = 0; i + (1 << j) - 1 < n; ++i) {
// cout << table[i][j] << ' ';
// }
// cout << '\n';
// }
return table;
}
//Computes the query in O(1) time using the sparse table
//Returns the minimum value from the interval [start,end]
ll computeQuery(vector<vector<int>>& table, vector<ll>& elements, int start, int end) {
int k = log2(end - start + 1), pos1 = table[start][k], pos2 = table[end - (1 << k) + 1][k];
return min(elements[pos1], elements[pos2]);
}
void Solve() {
int n,q;
fin >> n >> q;
vector<ll> v(n);
for (int i = 0; i < n; ++i) {
fin >> v[i];
}
auto table = computeSparseTable(v);
for (int i = 0; i < q; ++i) {
int x, y;
fin >> x >> y;
fout << computeQuery(table, v, x - 1, y - 1) << '\n';
}
}
int main() {
ios_base::sync_with_stdio(false);
Solve();
return 0;
}