Cod sursa(job #2818566)

Utilizator victorzarzuZarzu Victor victorzarzu Data 16 decembrie 2021 15:24:52
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
#define zeros(x) ((x ^ (x - 1)) & x)

using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");
int n, m;
int aib[100001];

void update(int position, int value)
{
  for(int i = position;i <= n;i += zeros(i))
    aib[i] += value;
}

int query(int position)
{
  int sum = 0;
  for(int i = position;i >= 1;i -= zeros(i))  
    sum += aib[i];
  return sum;
}

int cauta(int value)
{
  int rep;
  for(rep = 1;rep < n;rep <<= 1);
  for(int i = 0;rep;rep >>= 1)
    if(i + rep <= n && aib[i + rep] <= value)
      {
        i += rep;
        value -= aib[i];
        if(!value)
          return i;
      }
  return -1;
}

void read()
{
  f>>n>>m;
  int x;
  for(int i = 1;i <= n;++i)
    f>>x, update(i, x);
}

void solve()
{
  int t, x, y;
  for(int i = 1;i <= m;++i)
  {
    f>>t>>x;
    if(!t)
      f>>y, update(x, y);
    else if(t == 1)
      f>>y, g<<query(y) - query(x - 1)<<'\n';
    else 
      g<<cauta(x)<<'\n';
  }
}

int main()
{
  read();
  solve();
  return 0;
}