Cod sursa(job #2073964)

Utilizator leraValeria lera Data 23 noiembrie 2017 21:45:41
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#define Nmax 100005
using namespace std;

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

int aib[Nmax], x, y, n, k, ls, ld, mij, op, m;
void upd(int pos, int val)
{
    for(; pos <= n; pos += pos & (-pos))
        aib[pos] += val;
}
int query(int a, int b)
{
    int s1 = 0;
    int pos = a - 1;
    for(; pos; pos -= pos & (- pos))
        s1 += aib[pos];
    int s2 = 0;
    pos = b;
    for(; pos; pos -= pos & (-pos))
        s2 += aib[pos];
    return s2 - s1;
}
int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        fin >> x;
        upd(i, x);
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> op;
        if(op == 0)
        {
            fin >> x >> y;
            upd(x, y);
        }
        else if(op == 1)
        {
            fin >> x >> y;
            fout << query(x, y) << '\n';
        }
        else
        {
            fin >> k;
            ls = 1;
            ld = n;
            while(ls < ld)
            {
                mij = (ls + ld) / 2;
                if(query(1, mij) >= k)
                    ld = mij;
                else ls = mij + 1;
            }
            if(query(1, ls) == k)fout << ls << '\n';
            else fout << -1 << '\n';
        }
    }
    return 0;
}