Cod sursa(job #2602191)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 16 aprilie 2020 10:30:08
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

int v[MAXN], aib[MAXN];

int n;

int lsb(int x){
    return (x & -x);
}

void update(int pos, int val){
    while(pos <= n){
        aib[pos] += val;
        pos += lsb(pos);
    }
}

int query(int pos){
    int ans = 0;
    while(pos){
        ans += aib[pos];
        pos -= lsb(pos);
    }
    return ans;
}

int main()
{
    ifstream fin("aib.in");
    ofstream fout("aib.out");
    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);
    int m;
    fin >> n >> m;
    for(int i = 1; i <= n; ++i){
        fin >> v[i];
        update(i, v[i]);
    }
    while(m--){
        int c, a, b;
        fin >> c >> a;
        if(c < 2) fin >> b;
        if(c == 0) update(a, b);
        else if(c == 1) fout << query(b) - query(a - 1) << "\n";
        else{
            int pas = 1 << 30, rez = 0;
            while(pas){
                if(rez + pas <= n && aib[rez + pas] <= a){
                    a -= aib[rez + pas];
                    rez += pas;
                }
                pas /= 2;
            }
            if(a == 0 && rez > 0) fout << rez << "\n";
            else fout << -1 << "\n";
        }
    }
    return 0;
}