Cod sursa(job #3134393)

Utilizator ZiGabiZiTilica Gabriel Lucian ZiGabiZi Data 28 mai 2023 22:47:28
Problema Range minimum query Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>

using namespace std;

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

int N, M;
vector<int> Elemente;
vector<int> ArboreSegmente;
vector<int> Lazy;

void ConstruiesteArboreSegmente(int nod, int st, int dr) {
    if (st == dr) {
        ArboreSegmente[nod] = Elemente[st];
        return;
    }

    int mij = (st + dr) / 2;
    ConstruiesteArboreSegmente(2 * nod, st, mij);
    ConstruiesteArboreSegmente(2 * nod + 1, mij + 1, dr);
    ArboreSegmente[nod] = min(ArboreSegmente[2 * nod], ArboreSegmente[2 * nod + 1]);
}

void ActualizeazaLazy(int nod, int st, int dr, int stInt, int drInt, int valoare) {
    if (Lazy[nod] != 0) {
        ArboreSegmente[nod] += Lazy[nod];

        if (st != dr) {
            Lazy[2 * nod] += Lazy[nod];
            Lazy[2 * nod + 1] += Lazy[nod];
        }

        Lazy[nod] = 0;
    }

    if (stInt > dr || drInt < st)
        return;

    if (stInt <= st && drInt >= dr) {
        ArboreSegmente[nod] += valoare;

        if (st != dr) {
            Lazy[2 * nod] += valoare;
            Lazy[2 * nod + 1] += valoare;
        }

        return;
    }

    int mij = (st + dr) / 2;
    ActualizeazaLazy(2 * nod, st, mij, stInt, drInt, valoare);
    ActualizeazaLazy(2 * nod + 1, mij + 1, dr, stInt, drInt, valoare);
    ArboreSegmente[nod] = min(ArboreSegmente[2 * nod], ArboreSegmente[2 * nod + 1]);
}

int Interogare(int nod, int st, int dr, int stInt, int drInt) {
    if (Lazy[nod] != 0) {
        ArboreSegmente[nod] += Lazy[nod];

        if (st != dr) {
            Lazy[2 * nod] += Lazy[nod];
            Lazy[2 * nod + 1] += Lazy[nod];
        }

        Lazy[nod] = 0;
    }

    if (stInt > dr || drInt < st)
        return INT_MAX;

    if (stInt <= st && drInt >= dr)
        return ArboreSegmente[nod];

    int mij = (st + dr) / 2;
    int minStanga = Interogare(2 * nod, st, mij, stInt, drInt);
    int minDreapta = Interogare(2 * nod + 1, mij + 1, dr, stInt, drInt);
    return min(minStanga, minDreapta);
}

int main() {
    fin >> N >> M;

    Elemente.resize(N);
    for (int i = 0; i < N; i++)
        fin >> Elemente[i];

    int dimensiuneArbore = 4 * N;
    ArboreSegmente.resize(dimensiuneArbore);
    Lazy.resize(dimensiuneArbore);

    ConstruiesteArboreSegmente(1, 0, N - 1);

    for (int i = 0; i < M; i++) {
        int x, y;
        fin >> x >> y;

        int rezultat = Interogare(1, 0, N - 1, x - 1, y - 1);
        fout << rezultat << endl;
    }

    return 0;
}