Cod sursa(job #2182804)

Utilizator PetyAlexandru Peticaru Pety Data 22 martie 2018 17:19:56
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("aib.in");
ofstream fout ("aib.out");

int n, m, aib[100001], v[100001], cer, a, b, sp[100001];

void update (int poz, int val) {
  for(; poz <= n; poz += poz&-poz)
    aib[poz] += val;
}
int query (int poz) {
  int s = 0;
  for (; poz > 0; poz -= poz&-poz)
    s += aib[poz];
  return s;
}

int binary_search (int val) {
  int st = 1, dr = n; 
  while (st <= dr) {
    int mij = (st + dr) / 2;
    int t = query(mij);
    if (t == val)
      return mij;
    if (t < val)
      st = mij + 1;
    if (t > val)
      dr = mij - 1;
  }
  return -1;
}

int main()
{
  fin >> n >> m;
  for (int i = 1; i <= n; i++) {
    fin >> v[i];
    sp[i]= sp[i - 1] + v[i];
    aib[i] = sp[i] - sp[i - (i&-i)];  
  }
  for (int i = 1; i <= m; i++) {
    fin >> cer;
    if (cer == 0) {
      fin >> a >> b;
      update(a, b);    
    }
    if (cer == 1) {
      fin >> a >> b;
      if (a > b)
        swap(a, b); 
      fout << query(b) - query(a - 1) << "\n";
    }  
    if (cer == 2) {
      fin >> a;
      fout << binary_search(a) << "\n";
    }
  }
  return 0;
}