Cod sursa(job #2310008)

Utilizator AlexPop28Pop Alex-Nicolae AlexPop28 Data 30 decembrie 2018 13:52:36
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>
#define all(cont) cont.begin(), cont.end()
#define pb push_back
#define fi first
#define se second
#define DEBUG(x) cerr << (#x) << ": " << (x) << '\n'

using namespace std;

typedef pair <int, int> pii;
typedef vector <int> vi;
typedef long long ll;
typedef unsigned long long ull;

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

struct BIT {
  int n;
  vi bit;
  BIT (int _n) : n (_n) {
    bit.resize (_n + 5, 0);
  }

  inline int lsb (int x) {
    return (x & (-x));
  }

  void update (int pos, int val) {
    for (int i = pos; i <= n; i += lsb (i)) {
      bit[i] += val;
    }
  }

  int query (int pos) {
    int ans = 0;
    for (int i = pos; i >= 1; i -= lsb (i)) {
      ans += bit[i];
    }
    return ans;
  }

  int queryOnSegment (int left, int right) {
    return query (right) - query (left - 1);
  }

  int searchForSum (int sum) {
    int pow = 1;
    while (pow < n) pow <<= 1;
    for (int i = 0; pow >= 1; pow >>= 1) {
      if (i + pow <= n) {
        if (sum >= bit[i + pow]) {
          sum -= bit[i + pow];
          i += pow;
          if (sum == 0) return i;
        }
      }
    }
    return -1;
  }
};

int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
#ifdef LOCAL_DEFINE
  freopen (".in", "r", stdin);
#endif

  freopen ("aib.in",  "r", stdin);
  freopen ("aib.out", "w", stdout);

  int n, m;
  scanf ("%d %d\n", &n, &m);

  BIT bit (n);
  for (int i = 1; i <= n; ++i) {
    int x;
    scanf ("%d", &x);
    bit.update (i, x);
  }

  while (m--) {
    int type, a, b;
    scanf ("%d %d", &type, &a);

    if (type == 0) {
      scanf ("%d", &b);
      bit.update (a, b);
    } else if (type == 1) {
      scanf ("%d", &b);
      printf ("%d\n", bit.queryOnSegment (a, b));
    } else {
      printf ("%d\n", bit.searchForSum (a));
    }
  }

  fclose (stdin);
  fclose (stdout);
  return 0;
}