Cod sursa(job #2923028)

Utilizator TheRomulusIvan Remus TheRomulus Data 11 septembrie 2022 11:34:29
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#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;
}