Cod sursa(job #2454376)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 8 septembrie 2019 02:04:57
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 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 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, a, b;
        fin >> op;
        if (op == 0)
        {
            fin >> a >> b;
            Update(a, b);
        }
        else if (op == 1)
        {
            fin >> a >> b;
            fout << Query(b) - Query(a - 1) << "\n";
        }
        else
        {
            fin >> a;
            int st = 1, dr = n;
            bool gasit = 0;

            while (st <= dr && !gasit)
            {
                int mij = (st + dr) / 2;
                int sum = Query(mij);

                if (sum == a)
                {
                    fout << mij << "\n";
                    gasit = 1;
                }
                else if (a < sum)
                    dr = mij - 1;
                else
                    st = mij + 1;
            }

            if (!gasit)
                fout << -1 << "\n";
        }
    }
    return 0;
}