Cod sursa(job #2641440)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 11 august 2020 13:44:47
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>

using namespace std;

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

int n, m;
int bit[100001];

void Update(int pos, int val)
{
    while (pos <= n)
    {
        bit[pos] += val;
        pos += (pos & -pos);
    }
}

int Query(int pos)
{
    int sum = 0;
    while (pos > 0)
    {
        sum += bit[pos];
        pos -= (pos & -pos);
    }
    return sum;
}

int Search(int val)
{
    int left = 1, right = n, mid, q;

    while (left <= right)
    {
        mid = (left + right) / 2;
        q = Query(mid);

        if (q == val)
            return mid;

        if (q < val)
            left = mid + 1;
        else
            right = mid - 1;
    }

    return -1;
}

int main()
{
    f >> n >> m;
    for (int i=1; i<=n; i++)
    {
        int x; f >> x;
        Update(i, x);
    }

    for (int i=1; i<=m; i++)
    {
        int type; f >> type;
        if (type == 0)
        {
            int pos, val; f >> pos >> val;
            Update(pos, val);
        }
        else if (type == 1)
        {
            int left, right; f >> left >> right;
            g << Query(right) - Query(left - 1) << "\n";
        }
        else
        {
            int val; f >> val;
            g << Search(val) << "\n";
        }
    }

    return 0;
}