Cod sursa(job #2811010)

Utilizator victorzarzuZarzu Victor victorzarzu Data 30 noiembrie 2021 21:06:29
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 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, x, y, z;
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 found(int value)
{
  int rep, i;
  for(rep = 1;rep < n;rep <<= 1);
  for(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;
  for(int i = 1;i <= n;++i)
    f>>x, update(i, x);
}

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

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