Cod sursa(job #3309577)

Utilizator Grama2008Grama Andrei Teodor Grama2008 Data 6 septembrie 2025 15:11:22
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>

using namespace std;

const int N=1e5+5;

unsigned int bit[N],n,m;

unsigned int sum(int pos){
    unsigned int res=0;
    while (pos>0){
        res+=bit[pos];
        pos=pos&(pos-1);
    }
    return res;
}

unsigned int getsum(int l, int r){
    return sum(r)-sum(l);
}

void update(int pos, unsigned int b){
    while (pos<=(int)n){
        bit[pos]+=b;
        pos+=pos&(-pos);
    }
}

int getk(unsigned int a){
    if (a==0)return 0;
    unsigned int cur=0;
    int idx=0, pow2=1;
    while ((pow2<<1)<=(int)n)pow2<<=1;
    while (pow2){
        int i=pow2+idx;
        if (i<=(int)n && cur+bit[i]<a){
            cur+=bit[i];
            idx=i;
        }
        pow2>>=1;
    }
    if (idx+1<=(int)n){
        idx++;
    }
    else{
        return -1;
    }
    return(sum(idx)==a?idx:-1);
}

int main()
{
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin>>n>>m;
    for (int i=1;i<=(int)n;i++){
        int a;cin>>a;
        update(i, a);
    }
    while (m--){
        int op;cin>>op;
        if (op==0){
            int a,b;cin>>a>>b;
            update(a,b);
        }
        else if (op==1){
            int a,b;cin>>a>>b;
            cout<<getsum(a-1,b)<<'\n';
        }
        else if (op==2){
            unsigned int a;cin>>a;
            cout<<getk(a)<<'\n';
        }
    }
    return 0;
}