Cod sursa(job #3267367)

Utilizator abelesefBurduhos Abel abelesef Data 11 ianuarie 2025 11:13:11
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
using ll = long long;
int aib[100005];
int n,m,op,x,a,b;

void update(int i,int x) {
        for (int crt = i;crt<=n;crt+=(crt&-crt)) {
                aib[crt]+=x;
        }
}

int query(int i) {
        int s = 0;
        for (int j = i;j>=1;j-=j&(-j)) {
                s+=aib[j];
        }
        return s;
}

void create() {
        for (int i = 1;i<=n;++i) {
                fin>>x;
                update(i,x);
        }
}

int main() {
        fin>>n>>m;
        create();
        for (int i = 1;i<=m;++i) {
                fin>>op;
                if (op==0) {
                        fin>>a>>b;
                        update(a,b);
                } else if (op==1) {
                        fin>>a>>b;
                        fout<<query(b)-query(a-1)<<'\n';
                } else if (op==2) {
                        fin>>a;
                        int pos = 0;
                        int pow = 1;
                        while((pow<<1)<=n)
                                pow<<=1;
                        while(pow!=0) {
                                if (pos+pow<=n&&aib[pos+pow]<=a) {
                                        a-=aib[pos+pow];
                                        pos+=pow;
                                        pow>>=1;
                                } else {
                                        pow>>=1;
                                }
                        }
                        if (a!=0)
                                pos = -1;
                        fout<<pos<<'\n';
                }
        }
        return 0;
}