Cod sursa(job #2699087)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 23 ianuarie 2021 17:32:26
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
using namespace std;

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

int a[100001];

int query (int x)
{
    int rasp = 0;
    while (x > 0)
    {
        rasp = rasp + a[x];
        x = x - (x&(-x));
    }
    return rasp;
}

void update(int x, int n, int val)
{
    while (x <= n)
    {
        a[x] += val;
        x = x + (x & (-x));
    }
}

int cauta (int n, int s)
{
    int x, pas;
    for (pas = 1; pas <= n; pas <<= 1);
    pas = pas >> 1;

    for (x = 0; pas > 0; pas = pas >> 1)
    {
        if (x + pas <= n && s >= a[x + pas])
        {
            s = s - a[x + pas];
            x = x + pas;

            if (s == 0)
                return x;
        }
    }
    return -1;
}


int main()
{
    int n, m, i, t, a, b;
    fin >> n >> m;
    for (i = 1; i<=n; i++)
    {
        fin >> a;
        update (i, n, a);
    }
    for (i = 1; i<=m; i++)
    {
        fin >> t;
        if (t == 0)
        {
            fin >> a >>  b;
            update (a, n, b);
        }
        else if (t == 1)
        {
            fin >> a >> b;
            fout << query (b) - query (a-1) << '\n';
        }
        else
        {
            fin >> a;
            fout << cauta (n, a) << '\n';
        }
    }
    return 0;
}