Cod sursa(job #2238927)

Utilizator NewGloryMihnea Andreescu NewGlory Data 8 septembrie 2018 13:52:49
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <cstdio>

using namespace std;

typedef long long ll;

const int N = 100000 + 5;

int n, q;
ll aib[N];

void add (int poz, ll val) {
  for(int i = poz; i <= n; i += i & (-i)) {
    aib[i] += val;
  }
}

ll prefix (int poz) {
  ll ans = 0;
  for(int i = poz; i >= 1; i -= i & (-i)) {
    ans += aib[i];
  }
  return ans;
}

int main () {
  freopen("aib.in", "r", stdin);
  freopen("aib.out", "w", stdout);
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin>>n>>q;
  for (int i = 1; i <= n; i++) {
    ll x;
    cin>>x;
    add (i, x);
  }
  while (q--) {
    int type;
    cin>>type;
    if (type == 0) {
      int a;
      ll b;
      cin>>a>>b;
      add (a, b);
    }
    if (type == 1) {
      int Left, Right;
      cin>>Left>>Right;
      ll ans = prefix (Right) - prefix (Left - 1);
      cout<<ans<<"\n";
    }
    if (type == 2) {
      ll x;
      cin>>x;
      int r = 0, pas = (1 << 16);
      while (pas) {
        if (r + pas <= n && aib[r+pas] <= x) {
          r+=pas;
          x -= aib[r];
        }
        pas/=2;
      }
      if (x > 0 || r == 0) {
        cout<<"-1\n";
      }
      else {
        cout<<r<<"\n";
      }
    }
  }
  return 0;
}