Cod sursa(job #2983894)

Utilizator PalcPalcu Stefan Palc Data 23 februarie 2023 11:39:59
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, Q, aib[100005];

void Update(int p, int x)
{
    while (p <= n)
    {
        aib[p] += x;
        p += (p & (-p));
    }
}

int Query(int p)
{
    int suma = 0;
    while (p > 0)
    {
        suma += aib[p];
        p -= (p & (-p));
    }
    return suma;
}

int CB(int S)
{
    int st, dr, p, mij, x;
    st = 1; dr = n; p = -1;
    while (st <= dr)
    {
        mij = (st + dr) / 2;
        x = Query(mij);
        if (x == S) p = mij;
        if (x < S) st = mij + 1;
        else dr = mij - 1;
    }
    return p;
}

int main()
{
    int op, x, y;
    fin >> n >> Q;
    for (int i = 1; i <= n; i++)
    {
        fin >> x;
        Update(i, x);
    }
    while (Q--)
    {
        fin >> op;
        if (op == 0)
        {
            fin >> x >> y;
            Update(x, y);
        }
        else if (op == 1)
        {
            fin >> x >> y;
            fout << Query(y) - Query(x - 1) << "\n";
        }
        else
        {
            fin >> x;
            fout << CB(x) << "\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}