Cod sursa(job #2676352)

Utilizator paul3ioanCirstean Paul Ioan paul3ioan Data 24 noiembrie 2020 09:19:02
Problema Datorii Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.5 kb
#include <fstream>
using namespace std;
ifstream cin("datorii.in");
ofstream cout("datorii.out");
const int Nmax = 15005;
int n, m;
void build(int,int,int);
void update(int,int,int,int,int);
int query(int,int,int,int,int);
int arbore[Nmax * 4], v[Nmax];
int main() {
    cin >> n >> m;
    for(int i = 1 ;i <=n ;i ++)
        cin >> v[i];
    int tip, a, b;
    build(1,1,n);
    while(m--)
    {
        cin >> tip >> a >> b;
        if(tip)
            cout <<query(1, 1, n, a, b) << '\n';
        else
            update(1, 1, n, a, b);
    }
    return 0;
}
void build(int nod, int x, int y)
{
    if(x == y)
        arbore[nod] = v[x];
    else
    {
        int mij = (x + y) / 2;
        build(nod * 2, x, mij);
        build(nod * 2 + 1, mij + 1, y);
        arbore[nod] = arbore[nod * 2] + arbore[nod * 2 + 1];
    }
}
void update(int nod , int x, int y, int poz, int val)
{
    if(x == y)
        arbore[nod] -= val;
    else
    {
        int mij = (x + y) / 2;
        if(poz <= mij)
            update(nod * 2, x, mij, poz, val);
        else
            update(nod * 2 + 1, mij + 1, y, poz, val);
        arbore[nod] = arbore[nod * 2] + arbore[nod * 2 + 1];
    }
}
int query(int nod, int x, int y, int a ,int b)
{
    int val1 = 0, val2 = 0;
    if(a <=x and y <=b)
        return arbore[nod];
    else
    {
        int mij = (x + y) / 2;
        if(a <= mij)
            val1 = query(nod * 2, x, mij, a, b);
        if(mij < b)
            val2 = query(nod * 2 + 1, mij + 1, y, a ,b );
        return val1 + val2;
    }
}