Cod sursa(job #2062266)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 10 noiembrie 2017 10:11:05
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream in ("aib.in");
ofstream out ("aib.out");
int const nmax = 100000;
int v[5 + nmax];
int n ;
void update(int x ,int a){
  while(x <= n){
    v[x] += a;
    x += x ^ (x & (x - 1));
  }
}
int query(int x){
  int sum = 0;
  while(0 < x){
    sum += v[x];
    x &= x - 1;
  }
  return sum;
}
int binarysearch(int from ,int to ,int k){
  if(from < to){
    int mid = (from + to) / 2;
    if(query(mid) < k){
      return binarysearch(mid + 1 , to ,k);
    } else
      return binarysearch(from , mid ,k);
  } else
    return from;
}
int main()
{
  int m;
  in>>n>>m;
  int a;
  for(int i = 1 ; i <= n ;i++){
    in>>a;
    update(i , a);
  }
  for(int i = 1 ; i <= m ;i++){
    int op;
    in>>op;
    if(op == 0){
      int a , b;
      in>>a>>b;
      update(a , b);
    } else if(op == 1){
      int a , b;
      in>>a>>b;
      out<<query(b) - query(a - 1)<<'\n';
    } else{
      int k;
      in>>k;
      int result = binarysearch(1 , n , k);
      if(query(result) == k){
        out<<result<<'\n';
      } else
        out<<-1<<'\n';
    }
  }
  return 0;
}