Cod sursa(job #1706077)

Utilizator BrandonChris Luntraru Brandon Data 21 mai 2016 14:55:43
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <cmath>

using namespace std;

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

const int MaxN = 100005;

int BITree[MaxN];
int n, m, pow2;

inline void pow2Init() {
  for (pow2 = 1; pow2 <= n; pow2 <<= 1);
}

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

inline int Query(int pos) {
  int ans = 0;
  for (; pos; pos -= pos & (-pos)) ans += BITree[pos];
  return ans;
}

int QuerySearch(int val) {
  int pos, step;
  for (pos = 0, step = pow2; step; step >>= 1) {
    int newpos = pos + step;
    if (newpos <= n and BITree[newpos] <= val) {
      val -= BITree[newpos];
      pos = newpos;
    }
  }
  return !val ? pos : -1;
}

int main() {
  cin >> n >> m;
  pow2Init();
  for (int i = 1; i <= n; ++i) {
    int a;
    cin >> a;
    Update(i, a);
  }
  for (int i = 1; i <= m; ++i) {
    int op, a, b;
    cin >> op;
    if (op == 0){
      cin >> a >> b;
      Update(a, b);
    }
    else if (op == 1) {
      cin >> a >> b;
      cout << Query(b) - Query(a - 1) << '\n';
    }
    else {
      cin >> a;
      cout << QuerySearch(a) << '\n';
    }
  }
  return 0;
}