Cod sursa(job #2217704)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 1 iulie 2018 16:12:09
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
/**
  *  Worg
  */
#include <cstdio>
#include <vector>

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

FILE *fin = freopen("aib.in", "r", stdin); FILE *fout = freopen("aib.out", "w", stdout);

const int MAX_BIT = 18;

struct Fenwick {
  int size;
  std::vector<int > v;

  Fenwick(const int &n) {
    this->size = n; v = std::vector<int >(n + 1, 0);
  }

  void Add(const int position, const int value) {
    for(int i = position; i <= size; i += lsb(i)) {
      v[i] += value;
    }
  }

  long long Query(const int position) {
    long long ret = 0;
    for(int i = position; i > 0; i -= lsb(i)) {
      ret += v[i];
    }

    return ret;
  }

  int Search(const int searchedSum) {
    int k = 0;

    for(int i = MAX_BIT; i >= 0; i--) {
      if(k + (1 << i) > size) continue;

      if(Query(k + (1 << i)) <= searchedSum) {
        k += (1 << i);
      }
    }

    if(Query(k) == searchedSum && k > 0) {
      return k;
    } else {
      return -1;
    }
  }
};

int main() {
  //  Initialize data
  int n, m; scanf("%d%d", &n, &m);

  Fenwick fenwick = Fenwick(n);

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

  //  Process operations
  for(int i = 0; i < m; i++) {
    int type; scanf("%d", &type);

    if(type == 0) {
      int a, b; scanf("%d%d", &a, &b);
      fenwick.Add(a, b);
    } else if(type == 1) {
      int a, b; scanf("%d%d", &a, &b);
      long long ans = fenwick.Query(b) - fenwick.Query(a - 1);

      printf("%lld\n", ans);
    } else {
      int a; scanf("%d", &a);
      int ans = fenwick.Search(a);

      printf("%d\n", ans);
    }
  }

  return 0;
}