Cod sursa(job #3358871)

Utilizator ciucelizamariaeliza ciuc ciucelizamaria Data 21 iunie 2026 10:02:42
Problema Range minimum query Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<unordered_map>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;

ifstream fin("rmq.in");
ofstream fout("rmq.out");

/*struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

class InorderIterator {
    stack<Node*> st;

    void move_left(Node* node) {
        while (node != nullptr) {
            st.push(node);
            node = node->left;
        }
    }
public:
    InorderIterator(Node* root) {
        move_left(root);
    }

    bool hasNext() {
        return !(st.empty());
    }

    Node* next() {
        if (st.empty()) {
            throw "NO NEXT";
        }
        Node* current_node = st.top();
        st.pop();
        if (current_node->right != nullptr) {
            move_left(current_node->right);
        }

        return current_node;
    }
};*/

int e[100005];
int n, queries;
int a[100005];
int rmq[22][100005];

void read_data() {
    fin >> n >> queries;
    for (int i = 1; i <= n; i++) {
        fin >> a[i];
    }
}

void make_expo() {
    e[1] = 0;
    e[2] = 1;
    for (int i = 3; i <= 100000; i++) {
        e[i] = 1 + e[i / 2];
    }
}

void make_rmq() {
    for (int i = 1; i <= n; i++) {
        rmq[0][i] = a[i]; //[i, i + 2^0 - 1] = [i, i]
    }

    for (int i = 1; i <= e[n]; i++) {
        for (int j = 1; j <= n - (1 << i) + 1; j++) {
//        [j, j + 2^i - 1]
            rmq[i][j] = min(rmq[i - 1][j], rmq[i - 1][j + (1 << i - 1)]);
            //              [j, j + 2^(i - 1) - 1] [j + 2^(i - 1), j + 2^(i - 1) + 2^(i - 1) - 1]
            //                                                       2 * (2^(i - 1)) = 2^i
            //              [j, j + 2^(i - 1) - 1] [j + 2^(i - 1), j + 2^i - 1]
        }
    }
}

void solution() {
    make_expo();
    make_rmq();
    int x, y;
    for (int i = 1; i <= queries; i++) {
        fin >> x >> y; //[x, x + y - 1]
        int j = e[y - x + 1];
        int len = (1 << j);
        int sol = min(rmq[j][x], rmq[j][y - len + 1]);
        fout << sol << "\n";
    }
}

int main() {
    read_data();
    solution();
    fin.close();
    fout.close();
    return 0;
}