Cod sursa(job #2969910)

Utilizator sandry24Grosu Alexandru sandry24 Data 23 ianuarie 2023 21:19:10
Problema Arbori indexati binar Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>
using namespace std;
 
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pi;
#define pb push_back
#define mp make_pair
#define f first
#define s second

int n, m;
int BIT[100001];

void add(int x, int delta){
    for(; x <= n; x += x & -x)
        BIT[x] += delta;
}

int sum(int x){
    int sum = 0;
    for(; x > 0; x -= x & -x)
        sum += BIT[x];
    return sum;
}

void solve(){
    memset(BIT,0,sizeof(BIT));
    cin >> n >> m;
    int a[n];
    for(int i = 0; i < n; i++){
        scanf("%d", &a[i]);
        add(i+1, a[i]);
    }
    for(int i = 0; i < m; i++){
        int c, a, b;
        cin >> c;
        if(c == 0){
            cin >> a >> b;
            add(a, b);
        } else if(c == 1){
            cin >> a >> b;
            cout << sum(b) - sum(a-1) << '\n';
        } else {
            cin >> a;
            int i, step;
            for(step = 1; step < n; step <<= 1);
            bool found = 0;
            for(i = 0; step; step >>= 1){
                if(i + step <= n){
                    if(a >= BIT[i+step]){
                        i += step;
                        a -= BIT[i];
                        if(!a){
                            cout << i << '\n';
                            found = 1;
                            break;
                        }
                    }
                }
            }
            if(!found)
                cout << -1 << '\n';
        }
    }
}  
 
int main(){
    freopen("aib.in", "r", stdin);
    freopen("aib.out", "w", stdout);
    //ios::sync_with_stdio(0); cin.tie(0);
    int t = 1;
    //cin >> t;
    while(t--){
        solve();
    }
}