Cod sursa(job #2272612)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 30 octombrie 2018 14:14:12
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.7 kb
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
#define mp make_pair
#define CHECK(x) if(!(x)) return false;
#define CHECKRET(x, y) if(!(x)) return (y);
#define SKIP(x) if((x)) continue;
typedef pair<int, int> pii;

#ifdef INFOARENA
#define ProblemName "aib"
#else
#define ProblemName "fis"
#endif

#define InFile ProblemName ".in"
#define OuFile ProblemName ".out"

const int MAXN = 100010;
int aib[MAXN];
int N;

inline int lastbit(int x) {
  return x & (-x);
}

int query(int pos) {
  int ans = 0;
  for (; pos > 0; ans += aib[pos], pos -= lastbit(pos));
  return ans;
}

inline int qft(int l, int r) {
  int ans = query(r);
  if (l > 1) ans -= query(l - 1);
  return ans;
}

void update(int pos, int x) {
  for (; pos <= N; aib[pos] += x, pos += lastbit(pos));
}

int query2(int x) {
  int l = 1, r = N;
  int ans = 0;
  int found = INT_MAX;
  while (l < r) {
    int mid = l + (r - l) / 2;
    if (aib[mid] + ans == x) found = mid;
    if (aib[mid] + ans >= x)
      r = mid;
    else {
      ans += aib[mid];
      l = mid + 1;
    }
  }
  if (ans + qft(r, r) == x)
    found = min(found, r);
  if (found == INT_MAX) found = -1;
  return found;
}

int main() {
  assert(freopen(InFile, "r", stdin));
  assert(freopen(OuFile, "w", stdout));
  int M;
  scanf("%d%d", &N, &M);
  for (int i = 1; i <= N; ++i) {
    int x;
    scanf("%d", &x);
    update(i, x);
  }
  while (M--) {
    int qt;
    scanf("%d", &qt);
    if (qt == 0) {
      int a, x;
      scanf("%d%d", &a, &x);
      update(a, x);
    }
    else if (qt == 1) {
      int l, r;
      scanf("%d%d", &l, &r);
      printf("%d\n", qft(l, r));
    }
    else {
      int x;
      scanf("%d", &x);
      printf("%d\n", query2(x));
    }
  }
  return 0;
}