Cod sursa(job #2504445)

Utilizator GhSamuelGherasim Teodor-Samuel GhSamuel Data 4 decembrie 2019 22:12:27
Problema Range minimum query Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define Nmax 100005
#define Arbmax 262145
using namespace std;
int n, m, arb[Arbmax];

ifstream f("rmq.in");
ofstream g("rmq.out");

void updateTree(int node, int val, int ls, int rs, int a, int b)
{
    if (a <= ls && b >= rs) {
        arb[node] = val;
        return;
    }

    int mid = (ls + rs) / 2;
    if (a <= mid)
        updateTree(2 * node, val, ls, mid, a, b);
    if (mid < b)
        updateTree(2 * node + 1, val, mid + 1, rs, a, b);

    arb[node] = min(arb[2 * node], arb[2 * node + 1]);
}

int ask(int node, int ls, int rs, int a, int b)
{
    if (a <= ls && b >= rs)
        return arb[node];

    int A = INT_MAX;
    int B = INT_MAX;
    int mid = (ls + rs) / 2;
    if (a <= mid)
        A = ask(2 * node, ls, mid, a, b);
    if (mid < b)
        B = ask(2 * node + 1, mid + 1, rs, a, b);
    return min(A, B);
}

void read()
{
    f >> n >> m;

    int val;
    for (int i = 1; i <= n; ++i) {
        f >> val;
        updateTree(1, val, 1, n, i, i);
    }
}

void solve()
{
    int x, y;
    for (int i = 1; i <= m; ++i) {
        f >> x >> y;
        g << ask(1, 1, n, x, y) << "\n";
    }
}

int main()
{
    read();
    solve();
    return 0;
}