Cod sursa(job #2445210)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 3 august 2019 10:45:40
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>

using namespace std;

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

const int NMAX = 1e5;

int N, M, p;
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;
}

int Search(int s)
{
    int cursor = 0;

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

            if(s == 0)
                return cursor;
        }

    return -1;
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= N; i++)
    {

        int x;
        fin >> x;
        Update(i, x);

    }

    for(int i = 1; i <= M; i++)
    {

        int t;
        fin >> t;

        if(t == 2)
        {
            int a;
            fin >> a;
            fout << Search(a) << '\n';
        }
        else if(t == 1)
        {
            int a, b;
            fin >> a >> b;
            fout << Query(b) - Query(a - 1) << '\n';
        }
        else
        {
            int a, b;
            fin >> a >> b;
            Update(a, b);
        }
    }

    return 0;
}