Cod sursa(job #1621060)

Utilizator dumytruKana Banana dumytru Data 29 februarie 2016 16:14:47
Problema Arbori indexati binar Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <climits>

using namespace std;

unsigned twosComplement(unsigned index) {
    unsigned powTwo = 1;
    while(index >= powTwo) {
        powTwo = powTwo<<1;
    }
    powTwo -= 1;
    return (index ^ powTwo) + 1;
}

unsigned getParent(unsigned index) {
    return index - (twosComplement(index) & index);
}

unsigned getNext(unsigned index) {
    return index + (twosComplement(index) & index);
}

void updateBIT(vector<int> *tree, unsigned index, int value) {
    while(index <= tree->size()) {
        (*tree)[index] += value;
        index = getNext(index);
    }
}

int getSum(vector<int> *tree, unsigned index) {
    int newSum = 0;
    while(index>0) {
        newSum += (*tree)[index];
        index = getParent(index);
    }

    return newSum;
}

int getMinK(vector<int> *tree, int sum) {
    int index = 1, last_index;

    while(sum > 0) {
        last_index = index;
        index = getNext(index);

        if(index >= tree->size() || (*tree)[index] > sum) {
            sum -= (*tree)[last_index];
            index = last_index+1;
            if(index >= tree->size()) {
                return -1;
            }
        }
    }

    if(sum<0)
        return -1;

    return last_index;
}

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

    unsigned n, m, i, nr, a, b;
    vector<int> aib;
    //read n and m
    fin>>n>>m;

    aib.resize(n+1);

    for( i=0; i<=n; i++ ) {
        aib[i] = 0;
    }

    for( i=0; i<n; i++ ) {
        fin>>nr;
        updateBIT(&aib, i+1, nr);
    }

    for( i=0; i<m; i++) {
        fin>>nr;
        if(nr==0) {
            fin>>a>>b;
            updateBIT(&aib, a+1, b);
        }
        else if(nr==1) {
            fin>>a>>b;
            fout<<getSum(&aib, b) - getSum(&aib, a-1)<<endl;
        }
        else if(nr==2) {
            fin>>a;
            fout<<getMinK(&aib, a)<<endl;
        }
    }

    return 0;
}