Cod sursa(job #2771349)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 26 august 2021 19:23:12
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
using namespace std;

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

struct aib{
    vector<int> tree;

    void update(int pos, int value) {
        for (int i = pos; i <= tree.size(); i += (i & (-i))) {
            tree[i] += value;
        }
    }

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

};

int main() {
    ios::sync_with_stdio(0), fin.tie(0), fout.tie(0);
    int n, m;
    fin >> n >> m;
    aib arbib;
    arbib.tree.resize(n + 1);
    for (int i = 1; i <= n; ++i) {
        int x; fin >> x;
        arbib.update(i, x);
    }
    while (m--) {
        int cerinta; fin >> cerinta;
        if (cerinta == 0) {
            int a, b; fin >> a >> b;
            arbib.update(a, b);
        } else if (cerinta == 1) {
            int a, b; fin >> a >> b;
            fout << arbib.query(b) - arbib.query(a - 1) << '\n';
        } else {
            int a; fin >> a;
            int left = 1, right = n;
            while (left < right) {
                int mij = (left + right) / 2;
                if (arbib.query(mij) >= a) {
                    right = mij;
                } else {
                    left = mij + 1;
                }
            }
            if (arbib.query(left) == a) {
                fout << left << '\n';
            } else {
                fout << -1 << '\n';
            }
        }
    }
    return 0;
}