Cod sursa(job #2719810)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 10 martie 2021 12:31:25
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int NMax = 1e5;

int n, m, x;
int aib[NMax + 5];

void Update(int pos, int value){
    for (int i = pos; i <= n; i += i & (-i))
        aib[i] += value;
}

void Read(){
    fin >> n >> m;
    for (int i = 1; i <= n; i++){
        fin >> x;
        Update(i, x);
    }
}

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

int Position(int value){
    int pos = 0;
    for (int i = (1 << 17); i >= 1; i >>= 1)
        if (pos + i <= n && value >= aib[pos + i]){
            pos += i;
            value -= aib[pos];
            if (!value)
                return pos;
        }
    return -1;
}

int main(){
    Read();
    while (m--){
        int type;
        fin >> type;
        if (type == 0){
            int a, b;
            fin >> a >> b;
            Update(a, b);
        }
        if (type == 1){
            int a, b;
            fin >> a >> b;
            fout << Sum(b) - Sum(a - 1) << '\n';
        }
        if (type == 2){
            int a;
            fin >> a;
            fout << Position(a) << '\n';
        }
    }
    return 0;
}