Cod sursa(job #3240270)

Utilizator RaresHRares Hanganu RaresH Data 13 august 2024 18:35:01
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <stdio.h>

const int MAXN = 100'000;
const int MAX_LOG = 17;

int bit[MAXN + 1];
  
void update(int poz, int x, int n) {
  while(poz <= n) {
    bit[poz] += x;
    poz += poz & -poz;
  }
}
  
int query(int poz) {
  int rez = 0;

  while(poz > 0) {
    rez += bit[poz];
    poz &= poz - 1;
  }
  
  return rez;
}

int main() {
  FILE *fin, *fout;
  int n, m, i, t, a, b, sum, pos, p2;

  fin = fopen("aib.in", "r");
  fscanf(fin, "%d%d", &n, &m);
  for(i = 0; i < n; i++) {
    fscanf(fin, "%d", &a);
    update(i + 1, a, n);
  }
  fout = fopen("aib.out", "w");
  for(i = 0; i < m; i++) {
    fscanf(fin, "%d%d", &t, &a);

    if(t == 0) {
      fscanf(fin, "%d", &b);
      update(a, b, n);
    } else if(t == 1) {
      fscanf(fin, "%d", &b);
      fprintf(fout, "%d\n", query(b) - query(a - 1));
    } else {
      sum = 0;
      pos = 0;
      for(p2 = (1 << MAX_LOG); p2 > 0; p2 >>= 1) {
        if(pos + p2 <= n && sum + bit[pos + p2] <= a) {
          sum += bit[pos + p2];
          pos += p2;
        }
      }
      if(pos == 0)
        pos = 1;

      fprintf(fout, "%d\n", query(pos) == a ? pos : -1);
    }
  }
  fclose(fout);
  fclose(fin);

  return 0;
}