Cod sursa(job #2415638)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 26 aprilie 2019 13:12:20
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>

using namespace std;

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

const int NMAX = 100000;

int N, M;
int aib[NMAX + 5];

inline int LastBit(int x)
{
    return x & (-x);
}

void Update(int pos, int val)
{
    for(int i = pos; i <= N; i += LastBit(i))
        aib[i] += val;
}

int Query(int pos)
{
    int ans = 0;

    for(int i = pos; i > 0; i -= LastBit(i))
        ans += aib[i];

    return ans;
}

void Search(int x)
{
    int c = 0;
    int s = 0;

    for(int step = 16; step >= 0; step--)
        if(c + (1 << step) <= N)
            if(s + aib[c + (1 << step)] <= x)
            {
                s += aib[c + (1 << step)];
                c += (1 << step);
            }

    if(s == x)
        fout << c << '\n';
    else
        fout << -1 << '\n';
}

int main()
{
    int t, x, y;

    fin >> N >> M;

    for(int i = 1; i <= N; i++)
    {
        fin >> x;
        Update(i, x);
    }

    for(int i = 1; i <= M; i++)
    {
        fin >> t >> x;

        if(t == 0)
        {
            fin >> y;
            Update(x, y);
        }
        else if(t == 1)
        {
            fin >> y;
            fout << Query(y) - Query(x - 1) << '\n';
        }
        else
            Search(x);
    }

    return 0;
}