Cod sursa(job #2829246)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 8 ianuarie 2022 13:58:14
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n, m, pow2;
int fw[100005];

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

int query(int poz)
{
    int ans = 0;
    for(int i = poz; i >= 1; i -= (i & (-i)))
        ans += fw[i];
    return ans;
}

int cautbin(int val)
{
    int ans = 0, s = 0;
    for(int i = pow2; i >= 1; i >>= 1)
    {
        if((ans + i <= n) && (s + fw[ans + i] <= val))
           ans += i, s+= fw[ans];
    }
    if(s == val && ans != 0)
        return ans;
    else
        return -1;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        int a;
        fin >> a;
        update(i, a);
    }
    pow2 = 1;
    while(pow2 * 2 <= n)
        pow2 *= 2;
    for(int i = 1; i <= m; i++)
    {
        int op, x, y;
        fin >> op;
        if(op == 0)
        {
            fin >> x >> y;
            update(x, y);
        }
        if(op == 1)
        {
            fin >> x >> y;
            fout << query(y) - query(x - 1) << '\n';
        }
        if(op == 2)
        {
            fin >> x;
            fout << cautbin(x) << '\n';
        }
    }
    return 0;
}