Cod sursa(job #2952183)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 8 decembrie 2022 18:06:02
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <cmath>

using namespace std;

ifstream cin("aib.in");
ofstream cout("aib.out");

int a[100001], n, m;
int aib[100001];

int LSB(int n)
{
    return (n & (-n));
}

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

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

int FindPos(int value)
{
    int pos = 0;
    int sum = 0;
    int i = log2(n);
    while (i >= 0)
    {
        int curPos = pos + (1 << i);
        if (curPos <= n && sum + aib[curPos] < value)
        {
            pos = curPos;
            sum += aib[curPos];
        }
        i--;
    }

    return (Query(pos + 1) == value ? pos + 1 : -1);
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        cin >> a[i], Update(i, a[i]);

    for (int i = 1; i <= m; i++)
    {
        int tip, x, y;
        cin >> tip;
        if (tip == 0)
        {
            cin >> x >> y;
            Update(x, y);
        }
        else if (tip == 1)
        {
            cin >> x >> y;
            cout << Query(y) - Query(x - 1) << '\n';
        }
        else
        {
            cin >> x;
            cout << FindPos(x) << '\n';
        }
    }
    return 0;
}