Cod sursa(job #2461121)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 24 septembrie 2019 21:41:57
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
#define N 100005

using namespace std;

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

int n, m, aib[N];

int lowestBit(int x)
{
    return (x & -x);
}

void Update(int pos, int add)
{
    for (int i = pos; i <= n; i += lowestBit(i))
        aib[i] += add;
}

int Query(int pos)
{
    int sum = 0;
    for (int i = pos; i; i -= lowestBit(i))
        sum += aib[i];
    return sum;
}

int Search(int val)
{
    int pos = 0, Size;
    for (Size = 1; Size <= n; Size <<= 1);
    Size >>= 1;

    while (Size)
    {
        if (pos + Size <= n)
        {
            if (aib[pos + Size] <= val)
            {
                pos += Size;
                val -= aib[pos];

                if (!val)
                    return pos;
            }
        }

        Size >>= 1;
    }

    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 op;
        fin >> op;
        if (op == 0)
        {
            int pos, add;
            fin >> pos >> add;
            Update(pos, add);
        }
        else if (op == 1)
        {
            int st, dr;
            fin >> st >> dr;
            fout << Query(dr) - Query(st - 1) << "\n";
        }
        else
        {
            int val;
            fin >> val;
            fout << Search(val) << "\n";
        }
    }

    return 0;
}