Cod sursa(job #484250)

Utilizator Smaug-Andrei C. Smaug- Data 12 septembrie 2010 23:52:17
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <cstdio>
#include <string>

#define MAXN 100010

int N, M, T[MAXN], maxn;

void Update(int pos, int key){
  while(pos <= N){
    T[pos] += key;
    pos += pos^(pos&(pos-1));
  }
}

int Query(int pos){
  int aux = 0;
  while(pos > 0){
    aux += T[pos];
    pos -= pos^(pos&(pos-1));
  }
  return aux;
}

int Search(int key){
  
  int left = 0, mid, right = maxn;
  while(right && (left < N)){
    mid = left+right;
    if(T[mid] == key)
      return mid;
    else if(key > T[mid]){
      left = mid;
      key -= T[mid];
    }
    right >>= 1;
  }
  
  if(key)
    return left;
  else
    return -1;  
}

int main(){

  int i, aux, x, y;

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

  memset(T, 0, sizeof(T));

  scanf("%d%d", &N, &M);
  for(i = 1; i <= N; i++){
    scanf("%d", &aux);
    Update(i, aux);
  }

  aux = maxn = N;
  while(true){
    aux &= aux-1;
    if(!aux)
      break;
    maxn = aux;
  }
    
  printf("%d\n\n", maxn);

  while(M--){
    scanf("%d", &aux);
    if(aux < 2){
      scanf("%d%d", &x, &y);
      if(!aux)
	Update(x, y);
      else
	printf("%d\n", Query(y)-Query(x-1));
    }
    else {
      scanf("%d", &x);
      printf("%d\n", Search(x));
    }
  }

  return 0;

}