Cod sursa(job #2294559)

Utilizator TooHappyMarchitan Teodor TooHappy Data 2 decembrie 2018 16:04:48
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
 
using namespace std;

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

const int Nmax = 1e5 + 10;

int n, m, BIT[Nmax];

int getParent(int index) {
    return index - (index & -index);
}

int getNext(int index) {
    return index + (index & -index);
}

void updateTree(int value, int index) {
    while(index <= n) {
        BIT[index] += value;
        index = getNext(index);
    }
}

int getSum(int index) {
    int sum = 0;
    while(index > 0) {
        sum += BIT[index];
        index = getParent(index);
    }

    return sum;
}

int getPosition(int targetSum) {
    int step = (1 << 30);
    for(int i = 0; step; step >>= 1) {
        if(i + step <= n) {
            if(getSum(i + step) == targetSum) {
                return i + step;
            }
            if(getSum(i + step) < targetSum) {
                i += step;
            }
        }
    }

    return -1;
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);

    in >> n >> m;
    for(int i = 1; i <= n; ++i) {
        int value; in >> value;
        updateTree(value, i);
    }

    for(int i = 1; i <= m; ++i) {
        int type; in >> type;

        if(type < 2) {
            int a, b; in >> a >> b;
            
            if(type == 0) {
                updateTree(b, a);
            } else {
                out << getSum(b) - getSum(a - 1) << "\n";
            }
        } else {
            int a; in >> a;
            out << getPosition(a) << "\n";
        }
    }
 
    in.close(); out.close();
 
    return 0;
}