Cod sursa(job #1129250)

Utilizator toranagahVlad Badelita toranagah Data 27 februarie 2014 20:57:41
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

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

struct AIB {
  AIB(int _n=0) {
    n = _n;
    t.resize(n + 10, 0);
  }

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

  inline int query(int pos) const {
    int result = 0;
    for (int p = pos; p > 0; p -= (p & -p)) {
      result += t[p];
    }
    return result;
  }

  inline int find_sum(int sum) const {
    int step, pos;
    for (step = 1; step <= n; step *= 2);
    for (pos = 0; step > 0; step /= 2) {
      if (pos + step <= n) {
        if (t[pos + step] <= sum) {
          pos += step;
          sum -= t[pos];
        }
        if (sum == 0) return pos;
      }
    }
    return -1;
  }

  int n;
  vector<int> t;
};

int main() {
  int n, m;
  fin >> n >> m;
  AIB aib(n);

  for (int i = 1, x; i <= n; i += 1) {
    fin >> x;
    aib.update(i, x);
  }

  for (int i = 1, op, a, b; i <= m; i += 1) {
    fin >> op >> a;
    if (op == 0) {
      fin >> b;
      aib.update(a, b);
    } else if (op == 1) {
      fin >> b;
      fout << aib.query(b) - aib.query(a - 1) << '\n';
    } else {
      fout << aib.find_sum(a) << '\n';
    }
  }
  return 0;
}