Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <algorithm>
- #include <iostream>
- #include <vector>
- bool SortByVal(const std::pair<int, int>& a, const std::pair<int, int>& b) {
- return a.first < b.first;
- }
- class SparceTable {
- public:
- SparceTable(std::vector<int>& arr) {
- arr_ = arr;
- const size_t kSize = arr.size();
- size_t kHeight =
- static_cast<size_t>(std::log2(static_cast<double>(arr.size()))) + 1;
- for (size_t i = 0; i <= kHeight; ++i) {
- ST_.push_back({});
- ST_[i].assign(kSize + 1, {0, 0});
- }
- for (size_t i = 0; i < kSize; ++i) {
- ST_[0][i].first = i;
- ST_[0][i].second = INT32_MAX;
- }
- for (size_t i = 1; i <= kHeight; i++) {
- for (size_t j = 0; j + G(i) <= kSize; j++) {
- std::pair<int, int> new_min;
- new_min = Minimums(ST_[i - 1][j], ST_[i - 1][j + G(i - 1)]);
- ST_[i][j] = new_min;
- }
- }
- logs_.assign(kSize + 1, 0);
- logs_[1] = 0;
- logs_[0] = -1;
- for (size_t i = 2; i <= kSize; ++i) {
- logs_[i] = logs_[i / 2] + 1;
- }
- }
- std::pair<int, int> Minimums(std::pair<int, int>& fp,
- std::pair<int, int>& sp) {
- std::vector<int> indexes;
- indexes.push_back(fp.first);
- indexes.push_back(sp.second);
- indexes.push_back(fp.second);
- indexes.push_back(sp.first);
- std::sort(indexes.begin(), indexes.end());
- indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
- std::pair<int, int> res;
- std::vector<std::pair<int, int>> temp;
- for (size_t i = 0; i < indexes.size(); ++i) {
- if (indexes[i] == INT32_MAX) {
- temp.push_back({INT32_MAX, INT32_MAX});
- } else {
- temp.push_back({arr_[indexes[i]], indexes[i]});
- }
- }
- std::sort(temp.begin(), temp.end());
- res.first = temp[0].second;
- res.second = temp[1].second;
- return res;
- }
- int Query(size_t left, int right) {
- size_t i = static_cast<int>(logs_[right - left + 1]);
- std::pair<int, int> minimum =
- Minimums(ST_[i][left], ST_[i][right - G(i) + 1]);
- return minimum.second == INT32_MAX ? arr_[minimum.first]
- : arr_[minimum.second];
- // return arr_[minimum.second];
- }
- private:
- static size_t G(size_t x) { return 1 << x; }
- std::vector<std::vector<std::pair<int, int>>> ST_;
- std::vector<int> logs_;
- std::vector<int> arr_;
- };
- void Requests() {
- size_t n = 0;
- size_t m = 0;
- std::cin >> n >> m;
- int a = 0;
- std::vector<int> arr;
- for (size_t i = 0; i < n; ++i) {
- std::cin >> a;
- arr.push_back(a);
- }
- SparceTable table(arr);
- int l = 0;
- int r = 0;
- for (size_t i = 0; i < m; ++i) {
- std::cin >> l >> r;
- std::cout << table.Query(l - 1, r - 1) << "\n";
- }
- }
- int main() {
- Requests();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement