Cod sursa(job #2257121)

Utilizator Victor_InczeVictor Incze Victor_Incze Data 9 octombrie 2018 17:38:43
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
#define NMAX 100005
#define P(x) ( x&(-x) )

using namespace std;

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

int n, m, x, y, z, a[NMAX];

void ADD(int where, int what)
{
    for (int i=where; i<=n; i+=P(i))
        a[i]+=what;
}

int S(int x)
{
    int sum=0;
    for (int i=x; i>0; i-=P(i))
        sum+=a[i];
    return sum;
}

int suma(int p1, int p2)
{
    return S(p2)-S(p1-1);
}

int val(int x)
{
    int i=1;
    while (i<=n && a[i]<x)
    {
        if (i+P(i)<=n && a[i+P(i)]<=x)
        {
            i+=P(i);
            if (a[i]==x)
                return i;
        }
        if (i+P(i)<=n && a[i+P(i)]>x || i+P(i)>n)
        {
            x-=a[i];
            i++;
            if (a[i]==x)
                return i;
            if (i>n)
                return -1;
        }
    }
    if (a[i]==x)
        return i;
    return -1;
}

int main()
{
    in >> n >> m;
    for (int i=1; i<=n; i++)
    {
        in >> x;
        ADD(i,x);
    }
    for (int i=1; i<=m; i++)
    {
        in >> z;
        if (z==0)
        {
            in >> x >> y;
            ADD(x,y);
        }
        else
            if (z==1)
            {
                in >> x >> y;
                out << suma(x,y) << '\n';
            }
            else
            {
                in >> x;
                out << val(x) << '\n';
            }
    }
    return 0;
}