Cod sursa(job #1475476)

Utilizator salam1Florin Salam salam1 Data 24 august 2015 09:19:38
Problema Arbori indexati binar Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <cstdio>
const int NMAX = 100505;
int n, m, aib[NMAX];

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

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

int sum(int pos) {
  int res = 0;
  for ( ; pos ; pos -= lsb(pos))
    res += aib[pos];
  return res;
}

int get(int val) {
  int i = 0, step; 
  for (step = 1; step <= n; step <<= 1);
  
  for ( ; step; step >>= 1)
    if (i + step <= n && aib[i + step] <= val) {
      i += step;
      val -= aib[i];
    }
  return !val ? i : -1;
}

void read() {
  scanf("%d%d", &n, &m);
  int x;
  for (int i = 1; i <= n; i++) {
    scanf("%d", &x);
    update(i, x);
  }
}

void solve() {
  int type, a, b;
  while (m--) {
    scanf("%d", &type);
    switch (type) {
      case 0: {
        scanf("%d%d", &a, &b);
        update(a, b);
        break ;
      }
      case 1: {
        scanf("%d%d", &a, &b);
        printf("%d\n", sum(b) - sum(a - 1));
        break ;
      }
      case 2: {
        scanf("%d", &a);
        printf("%d\n", get(a));
        break ;
      }
    }
  }
}

int main() {
  freopen("aib.in", "r", stdin);
  freopen("aib.out", "w", stdout);
  
  read();
  solve();
  return 0;
}