Cod sursa(job #2544737)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 12 februarie 2020 13:58:50
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>

using namespace std;

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

const int NMAX = 1e5;

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

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

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

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

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

    return ans;
}

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

    for(int i = 18; i >= 0; i--)
        if(cursor + (1 << i) <= N && aib[cursor + (1 << i)] <= sum)
            {
                cursor += (1 << i);
                sum -= aib[cursor];

                if(sum == 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 type, a, b;
        fin >> type;

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

    return 0;
}