Cod sursa(job #3206782)

Utilizator juniorOvidiu Rosca junior Data 24 februarie 2024 07:13:49
Problema Datorii Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.78 kb
// 4
#include <fstream>
using namespace std;

#define MAX_N 15001

int N, M;
int a[4 * MAX_N]; // Folosim un vector mai mare pentru a stoca arborele de intervale

// Functie pentru construirea arborelui de intervale
void build(int nod, int l, int r, int valori[]) {
    if (l == r) {
        a[nod] = valori[l];
    } else {
        int m = (l + r) / 2;
        build(2 * nod, l, m, valori);
        build(2 * nod + 1, m + 1, r, valori);
        a[nod] = a[2 * nod] + a[2 * nod + 1];
    }
}

// Functie pentru actualizare (achitare)
void update(int nod, int l, int r, int poz, int val) {
    if (l == r) {
        a[nod] -= val;
    } else {
        int m = (l + r) / 2;
        if (poz <= m) {
            update(2 * nod, l, m, poz, val);
        } else {
            update(2 * nod + 1, m + 1, r, poz, val);
        }
        a[nod] = a[2 * nod] + a[2 * nod + 1];
    }
}

// Functie pentru interogare (suma dintr-un interval)
int query(int nod, int l, int r, int ql, int qr) {
    if (ql <= l && r <= qr) {
        return a[nod];
    }
    int m = (l + r) / 2;
    int sum = 0;
    if (ql <= m) {
        sum += query(2 * nod, l, m, ql, qr);
    }
    if (qr > m) {
        sum += query(2 * nod + 1, m + 1, r, ql, qr);
    }
    return sum;
}

int main() {
    ifstream fin("datorii.in");
    ofstream fout("datorii.out");

    fin >> N >> M;
    int valori[MAX_N];
    for (int i = 1; i <= N; i++) {
        fin >> valori[i];
    }

    build(1, 1, N, valori);

    for (int i = 0; i < M; i++) {
        int tip, x, y;
        fin >> tip >> x >> y;
        if (tip == 0) {
            update(1, 1, N, x, y);
        } else {
            fout << query(1, 1, N, x, y) << '\n';
        }
    }

    fin.close();
    fout.close();
    return 0;
}