Cod sursa(job #2717374)

Utilizator vlad082002Ciocoiu Vlad vlad082002 Data 7 martie 2021 12:16:32
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
using namespace std;

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

long long n, m, aib[100005];

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

long long query(long long pos) {
    long long sum = 0;
    for(long long i = pos; i > 0; i -= (i&(-i)))
        sum += aib[i];
    return sum;
}

long long bs(long long x) {
    long long l = 0, r = n, ans = -1;
    while(l <= r) {
        long long m = l+(r-l)/2;
        long long q = query(m);
        if(q >= x) {
            ans = m;
            r = m-1;
        } else {
            l = m+1;
        }
    }
    if(ans == -1 || query(ans) == x) return ans;
    return -1;
}

int main() {
    fin >> n >> m;
    for(long long i = 1; i <= n; i++) {
        long long a;
        fin >> a;
        update(a, i);
    }
    while(m--) {
        long long t, a, b;
        fin >> t;
        if(t == 0) {
            fin >> a >> b;
            update(b, a);
        } else if(t == 1) {
            fin >> a >> b;
            fout << query(b) - query(a-1) << '\n';
        } else {
            fin >> a;
            fout << bs(a) << '\n';
        }
    }
}