Cod sursa(job #2901866)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 14 mai 2022 17:32:23
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

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

int n, m;
int v[100005];

void Update(int pos, int val) {
    for (; pos <= n; pos += pos & (-pos)) {
        v[pos] += val;
    }
}

int Query(int pos) {
    int sum = 0;
    for (; pos > 0; pos -= pos & (-pos)) {
        sum += v[pos];
    }
    return sum;
}

int Query(int a, int b) {
    return Query(b) - Query(a - 1);
}

int BinarySearch(int val) {
    int sum = 0;
    int idx = 0;
    int pow = 1 << (int)(log2(n));
    while (pow > 0) {
        if (idx + pow <= n && sum + v[idx + pow] <= val) {
            sum += v[idx + pow];
            idx += pow;
        }
        pow /= 2;
    }

    if (idx == 0) {
        return -1;
    }
    return idx;
}


int main() {
    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        int val;
        fin >> val;
        Update(i, val);
    }

    for (int i = 1; i <= m; i++) {
        int t, a, b;
        fin >> t;
        if (t == 0) {
            fin >> a >> b;
            Update(a, b);
        }
        else if (t == 1) {
            fin >> a >> b;
            fout << Query(a, b) << '\n';
        }
        else {
            fin >> a;
            fout << BinarySearch(a) << '\n';
        }
    }
}