Cod sursa(job #855491)

Utilizator antonioteoZait Teodor Antonio antonioteo Data 14 ianuarie 2013 23:55:34
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <iostream>
#include <fstream>
using namespace std;
const char iname[] = "aib.in";
const char oname[] = "aib.out";
ifstream fin(iname);
ofstream fout(oname);
int n, m;
int a[100010];
inline int Suma(int x)
{
    int s = 0;
    while(x)
    {
        s+=a[x];
        x-=(x&-x);
    }
    return s;
}
inline void Update(int x, int y)
{
    while(x <= n)
    {
        a[x] += y;
        x+=(x&-x);
    }
}
inline int CautareBinara(int x)
{
    int mij, st, dr, s, sol, gasit = -1;
    st = 1; dr = n;
    while (st <= dr)
    {
        mij = (st + dr)/2;
        s = Suma(mij);
        if (s == x)
        {
            gasit = mij;
            dr = mij - 1;
        }
        else
            if (s > x)
                dr = mij - 1;
            else
                st = mij + 1;
    }
    if (gasit != -1)
        return gasit;
    return -1;
}
inline void Solve()
{
    fin >> n >> m;
    int i, x, y, cod;
    for(i = 1; i <= n; ++i)
    {
        fin >> x; Update(i, x);
    }
    int val1, val2;
    while(m--)
    {
        fin >> cod >> x;
        if (cod != 2)
            fin >> y;
        if (cod == 0)
            Update(x, y);
        else
		{
            if (cod == 1)
            {
                val1 = Suma(y);
                val2 = Suma(x-1);
                fout << (val1 - val2) << "\n";
            }
            else
            {
                val1 = CautareBinara(x);
                fout << val1 << "\n";
            }
		}
    }
}
int main()
{
    Solve();
    return 0;
}