Cod sursa(job #3204995)

Utilizator stefangab95Muscalu Stefan Gabriel stefangab95 Data 18 februarie 2024 15:25:32
Problema Range minimum query Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#define LS(p) 2*p+1
#define RS(p) 2*p+2
using namespace std;

const int MAXN = 1e5+5;
int tree[MAXN<<2];
void build(vector<int>& arr, int p, int lx, int rx) {
    if (lx == rx) {
        tree[p] = arr[lx];
    } else {
        build(arr, LS(p), lx, (lx+rx)/2);
        build(arr, RS(p), (lx+rx)/2+1, rx);
        tree[p] = min(tree[LS(p)], tree[RS(p)]);
    }
}
int getMin(int p, int lx, int rx, int x, int y) {
    if (lx > y || rx < x) return 1e5+5; // out of range
    if (lx >= x && rx <= y) return tree[p]; // in the range
    int mid = (lx+rx)/2;
    return min(getMin(LS(p), lx, mid, x, y), getMin(RS(p), mid+1, rx, x, y));
}
int main() {
    ifstream fin("rmq.in");
    ofstream fout("rmq.out");
    int N, M; fin >> N >> M;
    vector<int> arr(N);
    for (int i=0; i<N; ++i) fin >> arr[i];
    build(arr, 0, 0, N-1);
    while (M--) {
        int x, y; fin >> x >> y; --x, --y;
        fout << getMin(0, 0, N-1, x, y) << endl;
    }
    return 0;
}