Cod sursa(job #2307944)

Utilizator Victor_InczeVictor Incze Victor_Incze Data 25 decembrie 2018 22:18:26
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, v[100005];

void modify(int p, int value)
{
    while (p<=n)
    {
        v[p]+=value;
        p+=p&(p^(p-1));
    }
}

void citire()
{
    int x;
    in >> n >> m;
    for (int i=1; i<=n; i++)
    {
        in >> x;
        modify(i,x);
    }
}

int query(int x)
{
    int s=0;
    while (x>0)
    {
        s+=v[x];
        x-=x&(x^(x-1));
    }
    return s;
}

int binarysearch(int s)
{
    int step=1;
    while (step<n)
        step<<=1;
    for (int i=0; step; step>>=1)
        if (i+step<=n && v[i+step]<=s)
        {
            i+=step;
            s-=v[i];
            if (s==0)
                return i;
        }
    return -1;
}

void op()
{
    int p, x, y;
    for (int i=1; i<=m; i++)
    {
        in >> p;
        if (p==0)
        {
            in >> x >> y;
            modify(x,y);
        }
        else
            if (p==1)
            {
                in >> x >> y;
                out << query(y)-query(x-1) << '\n';
            }
            else
            {
                in >> x;
                out << binarysearch(x) << '\n';
            }
    }
}

void afis()
{
    for (int i=0; i<n; i++)
        out << v[i] << " ";
}

int main()
{
    citire();
    op();
    //afis();
    return 0;
}