Cod sursa(job #2453790)

Utilizator gabbie02Thomits Gabriel gabbie02 Data 6 septembrie 2019 02:22:30
Problema Datorii Scor 0
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <fstream>

using namespace std;

ifstream fin("datorii.in");

class BITree
{
private:
    short int * vals;
    unsigned short int sz;
public:
    BITree(unsigned short int siz)
    {
        sz = siz;
        vals = new short int[siz + 1]();
    }
    ~BITree()
    {
        delete[] vals;
    }
    void build()
    {
        unsigned short int ind;
        unsigned short int val;
        for(unsigned short int i = 1; i <= sz; i++){
            fin >> val;
            ind = i;
            while(ind <= sz){
                vals[ind] += val;
                ind += (ind & -ind);
            }
        }
    }
    void update(unsigned short int x, unsigned short int ind)
    {
        while(ind <= sz){
            if(vals[ind] != 0){
                vals[ind] -= x;
            }
            ind += (ind & -ind);
        }
    }
    unsigned short int sum(unsigned short int ind)
    {
        unsigned short int s = 0;
        while(ind > 0){
            s += vals[ind];
            ind -= (ind & -ind);
        }
        return s;
    }
};

int main()
{
    BITree * tr;
    ofstream fout("datorii.out");
    unsigned short int n, s, d, x;
    char t;
    fin >> n >> x;
    tr = new BITree(n);
    tr -> build();
    while(fin >> t){
        switch(t){
        case '0':
            fin >> d >> x;
            tr -> update(x, d);
            break;
        case '1':
            fin >> s >> d;
            fout << tr -> sum(d) - tr -> sum(s - 1) << '\n';
            break;
        }
    }
    return 0;
}