Cod sursa(job #1396432)

Utilizator rangerChihai Mihai ranger Data 22 martie 2015 15:20:12
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include<fstream>

using namespace std;


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


const int N = 100003;
int n,m,i,a[N],op,x,y;

void update(int pos, int val)
{
    while (pos<=n)
        a[pos]+=val, pos+=pos&-pos;
}

int sum(int pos)
{
    int ret=0;
    while (pos)
        ret += a[pos],
        pos -= pos&-pos;
    return ret;
}

int main()
{
    cin >> n >> m;

    for (i=1;i<=n;i++)
        cin >> x, update(i,x);

    while (m--)
    {
        cin >> op >> x;
        if (op == 2)
        {
            int l=1,r=n,gasit=0;

            while (l<=r && !gasit){
                int mi = (l+r)/2;
                int rs = sum(mi);
                if (rs>x) r=mi-1;
                else if (rs<x) l=mi+1;
                 else {
                    cout << mi << '\n';
                    gasit=1;
                 }
            }
            if (!gasit) cout << "-1\n";
        } else
         if (op == 0) cin >> y, update(x,y);
          else cin >> y, cout << sum(y) - sum(x-1) << '\n';
    }
    return  0;
}