Cod sursa(job #2225702)

Utilizator vladm98Munteanu Vlad vladm98 Data 28 iulie 2018 00:16:35
Problema Arbori indexati binar Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>

using namespace std;

unsigned int aib[100001];

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

void update (int n, int position, unsigned int value) {
    while (position <= n) {
        aib[position] += value;
        position += mostUnsignificantBit(position);
    }
}

unsigned int sumQuery (int position) {
    unsigned int currentSum = 0;
    while (position) {
        currentSum += aib[position];
        position -= mostUnsignificantBit(position);
    }
    return currentSum;
}

unsigned int intervalSum (int left, int right) {
    return sumQuery(right) - sumQuery(left - 1);
}

int findPosition (unsigned int currentSum, int n) {
    int currentPosition = 0;
    for (int power = 20; power >= 0; --power) {
        if (currentPosition + (1 << power) <= n and (aib[currentPosition + (1 << power)] < currentSum or
                (aib[currentPosition + (1 << power)] == currentSum and (power == 0 or
                        (aib[currentPosition + (1 << power - 1)] != currentSum))))) {
            currentSum -= aib [currentPosition + (1 << power)];
            currentPosition += (1 << power);
        }
    }
    return (currentSum == 0 and currentPosition ? currentPosition : - 1);
}

int main() {
    ifstream fin ("aib.in");
    ofstream fout ("aib.out");
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        unsigned int x;
        fin >> x;
        update(n, i, x);
    }
    for (int i = 1; i <= m; ++i) {
        int type;
        fin >> type;
        if (type == 0) {
            int position;
            unsigned int value;
            fin >> position >> value;
            update(n, position, value);
        }
        if (type == 1) {
            int left, right;
            fin >> left >> right;
            fout << intervalSum(left, right) << '\n';
        }
        if (type == 2) {
            unsigned int currentSum;
            fin >> currentSum;
            fout << findPosition(currentSum, n) << '\n';
        }
    }
    return 0;
}