Cod sursa(job #1708691)

Utilizator UPB_Darius_Rares_SilviuPeace my pants UPB_Darius_Rares_Silviu Data 27 mai 2016 20:03:11
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;

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

#define NMAX 100005
#define lsb(x) ((-x) & (x))

int N, M, aib[NMAX], tip, x, y;

void update(int pos, int value) {
    while (pos <= N) {
        aib[pos] += value;
        pos += lsb(pos);
    }
}

int query(int pos) {
    int res = 0;
    while (pos) {
        res += aib[pos];
        pos -= lsb(pos);
    }

    return res;
}

int main() {
    f >> N >> M;
    for (int i = 1; i <= N; ++i) {
        f >> x;
        update(i, x);
    }
    while (M--) {
        f >> tip >> x;
        if (tip == 0) {
            f >> y;
            update(x, y);
        } else if (tip == 1) {
            f >> y;
            g << query(y) -  query(x - 1) << '\n';
        } else {
            int pos = 0;
            for (int step = (1 << 30); step; step >>= 1) {
                if (pos + step <= N && query(pos + step) <= x) {
                    pos += step;

                    if (query(pos) == x) {
                        break;
                    }
                }
            }

            if (query(pos) != x) {
                g << -1 << '\n';
            } else {
                g << pos << '\n';
            }
        }
    }
    return 0;
}