Cod sursa(job #2917817)

Utilizator EusebiudistrugatorulLionel Messi Eusebiudistrugatorul Data 7 august 2022 22:14:26
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>
#define ll long long
#define ii pair<int, int>
using namespace std;
ifstream fin("aib.in");
ofstream fout("aib.out");

class FenwickTree {
// Change update and query accordingly
// Change initial value of carry
// Change type if needed
// Index from 0 if needed
private:
    int size;
    vector<int> tree;
public:
    FenwickTree(int curSize, int value) {
        this->size = curSize;
        tree.resize(curSize + 1, value);
    }

    void update(int pos, int value) {
        while (pos <= this->size) {
            this->tree[pos] += value;
            pos |= pos + 1;
        }
    }

    int query(int rightBound) {
        int carry = 0;
        while (rightBound > 0) {
            carry += this->tree[rightBound];
            rightBound = (rightBound & (rightBound + 1)) - 1;
        }
        return carry;
    }
};

int32_t main() {
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    int n, m;
    fin >> n >> m;
    FenwickTree tree(n, 0);
    for (int i = 1; i <= n; ++i) {
        int value;
        fin >> value;
        tree.update(i, value);
    }
    while (m--) {
        int type;
        fin >> type;
        if (type == 0) {
            int pos, add;
            fin >> pos >> add;
            tree.update(pos, add);
        } else if (type == 1) {
            int l, r;
            fin >> l >> r;
            int sumR = tree.query(r), sumL = tree.query(l - 1);
            fout << sumR - sumL << '\n';
        } else {
            int value;
            fin >> value;
            int l = 1, r = n;
            while (l < r) {
                int mid = (l + r) / 2;
                if (tree.query(mid) >= value) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            if (tree.query(l) == value) {
                fout << l << '\n';
            } else {
                fout << "-1\n";
            }
        }
    }
    return 0;
}