Cod sursa(job #1896193)

Utilizator preda.andreiPreda Andrei preda.andrei Data 28 februarie 2017 15:38:41
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>

using namespace std;

inline int ZeroPow(int n) { return n & -n; }

void Update(vector<int> &aib, unsigned pos, int val)
{
    while (pos < aib.size()) {
        aib[pos] += val;
        pos += ZeroPow(pos);
    }
}

int GetSum(const vector<int> &aib, int pos)
{
    int sum = 0;
    while (pos > 0) {
        sum += aib[pos];
        pos -= ZeroPow(pos);
    }
    return sum;
}

int FindPos(const vector<int> &aib, int sum)
{
    unsigned pos = 0;
    int pow = (1 << 25);

    while (pow > 0) {
        if (pos + pow < aib.size() && GetSum(aib, pos + pow) < sum) {
            pos += pow;
        }
        pow >>= 1;
    }

    if (pos + 1 < aib.size() && GetSum(aib, pos + 1) == sum) {
        return pos + 1;
    }
    return -1;
}

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

    int n, m;
    fin >> n >> m;

    vector<int> aib(n + 1, 0);
    for (int i = 1; i <= n; ++i) {
        int x;
        fin >> x;
        Update(aib, i, x);
    }

    while (m--) {
        int r, x, y;
        fin >> r >> x;

        if (r == 0) {
            fin >> y;
            Update(aib, x, y);
        } else if (r == 1) {
            fin >> y;
            fout << GetSum(aib, y) - GetSum(aib, x - 1) << "\n";
        } else {
            int pos = FindPos(aib, x);
            fout << pos << "\n";
        }
    }

    return 0;
}