Cod sursa(job #3287637)

Utilizator Zander012Unguru Alexandr-Ionut Zander012 Data 18 martie 2025 19:20:38
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");
const int nmax = 1e5;
int n,m;
int v[nmax+5];
int aib[nmax+5];
int ub(int x)
{
    return (x & (-x));
}
void add(int x, int val)
{
    for(int i=x; i<=n; i+=ub(i))
    {
        aib[i] += val;
    }
}
int sum(int x)
{
    int rez = 0;
    for(int i=x; i>=1; i-=ub(i))
    {
        rez += aib[i];
    }
    return rez;
}

int main()
{

    fin >>n >> m;
    for(int i=1; i<=n; i++)
    {
        fin >> v[i];
        add(i, v[i]);
    }
    for(int i=1; i<=m; i++)
    {
        int tip;
        fin >> tip;
        if(tip ==0)
        {
            int poz, val;
            fin >> poz >> val;
            add(poz,val);
        }
        else if(tip ==1)
        {
            int a, b;
            fin >>a >> b;
            fout<<sum(b)- sum(a-1)<<'\n';
        }
        else
        {
            int a,s=0, poz=0;

            fin>>a;
            for(int b=17; b>=0; b--)
            {
                if(poz + (1<<b) <= n && s + aib[poz + (1<<b)] < a)
                {
                    s += aib[poz + (1<<b)];
                    poz += (1<<b);
                }
            }
            if(poz + 1 > n || sum(poz + 1) != a)
            {
                fout << -1 << '\n';
            }
            else
            {
                fout<< poz + 1 << '\n';
            }
        }
    }
    return 0;
}