Cod sursa(job #1129332)

Utilizator toranagahVlad Badelita toranagah Data 27 februarie 2014 21:28:54
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

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

const int MAX_N = 100100;

int n, m;
int aib[MAX_N];

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

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

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

int main() {
  fin >> n >> m;

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

  for (int i = 1, op, a, b; i <= m; i += 1) {
    fin >> op >> a;
    if (op < 2) fin >> b;

    if (op == 0) {
      update(a, b);
    } else if (op == 1) {
      fout << query(b) - query(a - 1) << '\n';
    } else {
      fout << find_sum(a) << '\n';
    }
  }
  return 0;
}