Cod sursa(job #2931843)

Utilizator divadddDavid Curca divaddd Data 1 noiembrie 2022 00:40:01
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#define MAX 100002
using namespace std;
int n,a[MAX],x,y,t,q,v[MAX];

ifstream fin("aib.in");
ofstream fout("aib.out");

void update(int pos, int val){
    v[pos] += val;
    for(int i = pos; i <= n; i += (i&-i)){
        a[i] += val;
    }
}

int query(int pos){
    int ans = 0;
    for(int i = pos; i > 0; i -= (i&-i)){
        ans += a[i];
    }
    return ans;
}

int main()
{
    fin >> n >> q;
    for(int i = 1; i <= n; i++){
        fin >> x;
        update(i, x);
    }
    while(q--){
        fin >> t >> x;
        if(t == 0){
            fin >> y;
            update(x, y);
        }else if(t == 1){
            fin >> y;
            fout << query(y)-query(x-1) << "\n";
        }else{
            int st = 1, dr = n;
            /// 1 1 1 1 0 0 0 0
            ///       ^
            int ans = -1;
            while(st <= dr){
                int mid = (st+dr)/2;
                if(query(mid) <= x){
                    ans = mid;
                    st = mid+1;
                }else{
                    dr = mid-1;
                }
            }
            if(query(ans) == x){
                fout << ans << "\n";
            }else{
                fout << "-1\n";
            }
        }
    }
    return 0;
}