Cod sursa(job #2904725)

Utilizator DariaClemClem Daria DariaClem Data 18 mai 2022 00:55:55
Problema Range minimum query Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;

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

int numere[100001], arbore[400004], nrNumere, nrOperatii;

void construireArbore(int stanga, int dreapta, int index) {
    if (stanga == dreapta)
        arbore[index] = numere[stanga];
    else {
        int mij = stanga + (dreapta - stanga) / 2;
        construireArbore(stanga, mij, index << 1);
        construireArbore(mij + 1, dreapta, (index << 1) + 1);
        arbore[index] = min(arbore[index << 1],
                            arbore[(index << 1) + 1]);
    }
}

int determinareMinim(int a, int b, int stanga, int dreapta, int index) {
    if (a <= stanga and dreapta <= b) {
        return arbore[index];
    } else {
        if (a <= dreapta and b >= stanga) {
            int mij = stanga + (dreapta - stanga) / 2;
            return min(determinareMinim(a, b, stanga, mij, index << 1),
                       determinareMinim(a, b, mij + 1, dreapta, (index << 1) + 1));
        }
    }
    return 100001;
}

int main() {
    int index, operatie, a, b, stanga = 1, dreapta;
    fin >> nrNumere >> nrOperatii;
    dreapta = nrNumere;
    for (index = 1; index <= nrNumere; index += 1) {
        fin >> numere[index];
    }
    construireArbore(stanga, dreapta, 1);
    for (index = 1; index <= nrOperatii; index += 1) {
        fin >> a >> b;
        fout << determinareMinim(a, b, stanga, dreapta, 1) << "\n";
    }
    return 0;
}