Cod sursa(job #1955733)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 6 aprilie 2017 10:29:59
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>

using namespace std;

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

const int NMAX = 1e5 + 1;

int n, m;
int aib[NMAX];

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

inline int query(int pos) {
    int s = 0;
    for (int i = pos; i; i -= i & -i)
        s += aib[i];
    return s;
}

inline int searchPos(int val) {
    int ans = 0, step = 1;
    for (; (step << 1) <= n; step <<= 1);

    for (; step; step >>= 1) {
        if (ans + step <= n && val >= aib[ans + step]) {
            ans += step;
            val -= aib[ans];
            if (!val)
                return ans;
        }
    }
    return -1;
}

inline void read() {
    int x;
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        fin >> x;
        update(i, x);
    }
}

inline void solve() {
    int op, x, y;
    for (int i = 1; i <= m; ++i) {
        fin >> op;
        if (op == 0) {
            fin >> x >> y;
            update(x, y);
        }
        else if (op == 1) {
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        else {
            fin >> x;
            fout << searchPos(x) << '\n';
        }
    }
}

int main()
{
    read();
    solve();
    fin.close();
    fout.close();
    return 0;
}