Cod sursa(job #2532587)

Utilizator trifangrobertRobert Trifan trifangrobert Data 27 ianuarie 2020 23:17:07
Problema Arbori indexati binar Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 100005;
const int MAXSTEP = (1 << 20);
int N, M, aib[NMAX];

int lsb(int x)
{
    return (x & (-x));
}

void Update(int pos, int val)
{
    for (int i = pos;i <= N;i += lsb(i))
        aib[i] += val;
}

int Query(int pos)
{
    int sum = 0;
    for (int i = pos;i >= 1;i -= lsb(i))
        sum += aib[i];
    return sum;
}

int BinarySearch(int key)
{
    int pos = 0;
    for (int step = MAXSTEP;step >= 1;step /= 2)
    {
        if (pos + step <= N && key >= aib[pos + step])
        {
            key -= aib[pos + step];
            pos += step;
        }
    }
    if (key != 0)
        pos = -1;
    return pos;
}

int main()
{
    ifstream fin("aib.in");
    ofstream fout("aib.out");
    fin >> N >> M;
    for (int i = 1;i <= N;++i)
    {
        int x;
        fin >> x;
        Update(i, x);
    }
    for (int i = 1;i <= M;++i)
    {
        int op, a, b;
        fin >> op;
        if (op == 0)
        {
            fin >> a >> b;
            Update(a, b);
        }
        else if (op == 1)
        {
            fin >> a >> b;
            fout << Query(b) - Query(a - 1) << "\n";
        }
        else
        {
            fin >> a;
            fout << BinarySearch(a) << "\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}