Cod sursa(job #2676950)

Utilizator butasebiButa Gabriel-Sebastian butasebi Data 25 noiembrie 2020 15:33:21
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
using namespace std;
long long aib[100005];
int n, q, i, x, a, b, poz, st, dr, aux, op;
int LastBit(int x)
{
    return x & (-x);
}
void add_aib(int poz, int val)
{
    for(int i = poz;i <= n; i = i + LastBit(i))
        aib[i] = aib[i] + val;
}
int sum_aib(int poz)
{
    int s = 0;
    for(int i = poz; i > 0; i = i - LastBit(i))
        s = s + aib[i];
    return s;
}
int main()
{
    ifstream f("aib.in");
    ofstream g("aib.out");
    f >> n >> q;
    for(i = 1; i <= n; i ++)
    {
        f >> x;
        add_aib(i, x);
    }
    for(i = 1; i <= q; i ++)
    {
        f >> op;
        if(op == 0)
        {
            f >> a >> b;
            add_aib(a, b);
        }
        if(op == 1)
        {
            f >> a >> b;
            g << sum_aib(b) - sum_aib(a - 1) << "\n";
        }
        if(op == 2)
        {
            f >> a;
            poz = -1;
            st = 1;
            dr = n;
            while(st <= dr)
            {
                int mij = (st + dr) / 2;
                aux = sum_aib(mij);
                if(aux == a)poz = mij, st = dr + 1;
                else if(aux < a)st = mij + 1;
                else dr = mij - 1;
            }
            g << poz << "\n";
        }
    }
    return 0;
}