Cod sursa(job #3242057)

Utilizator CondoracheAlexandruCondorache Alexandru CondoracheAlexandru Data 8 septembrie 2024 14:45:24
Problema Arbori indexati binar Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define F first
#define S second
#define endl '\n'
#define all(a) (a).begin(),(a).end()
using namespace std;
const int maxn = 1e5 + 5;

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

class FenwickTree {
public:
    FenwickTree(int n);
    FenwickTree(vector<int> const &a);
    int query(int r);
    int sum(int l, int r);
    void update(int idx, int delta);
    void rangeUpdate(int l, int r, int val);
    int foo(int a);
public:
    vector<int> bit;
    int n;
};
 
FenwickTree::FenwickTree(int n) {
    this->n = n;
    bit.assign(n, 0);
}

FenwickTree::FenwickTree(vector<int> const &a) : FenwickTree(a.size()) {
    for (int i = 0; i < n; i++) {
        bit[i] += a[i];
        int r = i | (i + 1);
        if (r < n) bit[r] += bit[i];
    } 
}

int FenwickTree::query(int r) {
    int sum = 0;
    for (; r >= 0; r = (r & (r + 1)) - 1) {
        sum += bit[r];
    }
    return sum;
}

int FenwickTree::sum(int l, int r) {
    return query(r) - query(l - 1);
}

void FenwickTree::update(int idx, int delta) {
   for (; idx < n; idx = idx | (idx + 1)) {
        bit[idx] += delta;
    }
}


void FenwickTree::rangeUpdate(int l, int r, int val) {
    update(l, val);
    update(r + 1, -val);
}

int FenwickTree::foo(int a) {
    int l = 0;
    int r = bit.size() - 1;
    while (l <= r) {
        int mid = l + (r - l) / 2;
        if (query(mid) >= a) {
            r = mid - 1;
        }
        else {
            l = mid + 1;
        }
    }
    if (query(l) == a) {
        return l + 1;
    }
    else {
        return -1;
    }
}

void solve() {
    int n, q;
    fin >> n >> q;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        fin >> a[i];
    }
    FenwickTree tree(a);
    while (q--) {
        int type;
        fin >> type;
        if (type == 0) {
            int a, b;
            fin >> a >> b;
            a--;
            tree.update(a, b);
        }
        else if (type == 1) {
            int a, b;
            fin >> a >> b;
            a--;
            b--;
            fout << tree.sum(a, b) << endl;
        }
        else {
            int a;
            cin >> a;
            fout << tree.foo(a) << endl;
        }
    }
}
 
int main() {
    int t = 1;
    // cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}