Cod sursa(job #3147075)

Utilizator AdiFBubuBubuianu Adrian AdiFBubu Data 23 august 2023 23:45:34
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("aib.in");
ofstream g("aib.out");

int a[100010], N, M;

void update(int poz, int val)
{
    for(int i = poz; i <= N; i += i & (-i) )
        a[i] += val;
}

int sum(int poz)
{
    int suma = 0;
    for(int i = poz; i > 0; i -= i & (-i) )
        suma += a[i];
    return suma;
}

int query(int val)
{
    int step;
    for(step = 1; step < N; step = step << 1);

    for(int i = 0; step; step = step >> 1)
        if(i + step <= N)
        {
            if(val >= a[i + step])
            {
                i = i + step, val = val - a[i];
                if(val == 0)
                    return  i;
            }
        }
    return -1;
}

int main()
{
    f >> N >> M;
    int nr, tip;
    for(int i = 1; i <= N; i ++)
    {
        f >> nr;
        update(i, nr);
    }

    int x, y;
    for(int i = 1; i<= M; i ++)
    {
        f >> tip;
        if(tip == 0)
        {
            f >> x >> y;
            update(x, y);
        }
        else if(tip == 1)
        {
            f >> x >> y;
            g << sum(y) - sum(x - 1) << '\n';
        }
        else
        {
            f >> x;
            g << query(x) << '\n';
        }
    }
    return 0;
}