Cod sursa(job #2371451)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 6 martie 2019 17:40:35
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <map>
#include <stack>
#define ll long long
#define lsb(x) (x & -x)

using namespace std;

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

const int NMAX = 100005;
int aib[NMAX];

void update(int pos, int toadd, int n) {
    for(; pos <= n; pos += lsb(pos))
        aib[pos] += toadd;
}

int query(int pos) {
    int ans = 0;
    for(; pos; pos -= lsb(pos))
        ans += aib[pos];
    return ans;
}

int main() {

    int n, m;
    in >> n >> m;
    for(int i = 1; i <= n; i ++) {
        int x;
        in >> x;
        update(i, x, n);
    }

    while(m --) {
        int type;
        in >> type;
        if(type == 0) {
            int a, b;
            in >> a >> b;
            update(a, b, n);
        } else if(type == 1) {
            int a, b;
            in >> a >> b;
            out << query(b) - query(a - 1) << "\n";
        } else if(type == 2) {
            int a;
            in >> a;

            int ans = 0, flag = 0;
            for(int step = (1 << 16); step; step >>= 1) {
                if(ans + step <= n && aib[ans + step] <= a) {
                    ans += step;
                    a -= aib[ans];

                    if(a == 0) {
                        flag = 1;
                        out << ans << "\n";
                    }
                }
            }

            if(!flag)
                out << -1 << "\n";
        }
    }

    return 0;
}