Cod sursa(job #3256971)

Utilizator RaresPoinaruPoinaru-Rares-Aurel RaresPoinaru Data 16 noiembrie 2024 12:50:33
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("aib.in");
ofstream fout ("aib.out");
#define int long long

const int MAXN=1e5+10;

int n,q,a[MAXN],aib[MAXN];

void update (int pos, int val){
    for (int i=pos;i<=n;i+=(i&(-i))){
        aib[i]+=val;
    }
}
int query (int pos){
    int rez=0;
    for (int i=pos;i>=1;i-=(i&(-i))){
        rez+=aib[i];
    }
    return rez;
}
int query (int a, int b){
    return query (b)-query (a-1);
}

int solve (int x){
    if (x==0) return -1;
    int pos=0;
    for (int i=20;i>=0;--i){
        if (pos+(1<<i)>n) continue;
        if (aib[pos+(1<<i)]<=x){
            pos+=(1<<i);
            x-=aib[pos];
        }
    }
    if (x==0){
        return pos;
    }
    return -1;
}

signed main()
{

    fin >>n>>q;
    for (int i=1;i<=n;++i){
        fin >>a[i];
        update (i,a[i]);
    }
    for (int i=1;i<=q;++i){
        int t,x,y;
        fin >>t;
        if (t==0){
            fin >>x>>y;
            update (x,y);
        }
        else{
            if (t==1){
                fin >>x>>y;
                fout <<query (x,y)<<'\n';
            }
            else{
                fin >>x;
                fout <<solve (x)<<'\n';
            }
        }

    }
    return 0;
}