Cod sursa(job #2763454)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 14 iulie 2021 11:30:27
Problema Arbori indexati binar Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <bits/stdc++.h>
#define ll long long
#define nl '\n'
#define FOR(i, a, b) for (int i = a; i <= b; ++i) 
#define F0R(i, a, b) for (int i = a; i >= b; --i)
#define FORd(i, n) for (int i = 0; i < n; ++i)
#define F0Rd(i, n) for (int i = n - 1; i >= 0; --i)
#define trav(a, x) for (auto &a : x)
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
using namespace std;

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int mxN = 1e5 + 5;

int N, Q, Arb[mxN];

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

void Update(int node, int val) {
    for (int i = node; i <= N; i += (i & (-i))) {
        Arb[i] += val;
    }
}

int Query(int node) {
    int S = 0;
    for (int i = node; i > 0; i -= (i & (-i))) {
        S += Arb[i];
    }
    return S;
}

int Search(int Left, int Right, int k) {
    int mij = (Left + Right) / 2;
    int sum = Query(mij);
    if (sum == k) {
        return mij;
    }
    if (Left == Right && sum != k) {
        return -1;
    }
    if (sum >= k) {
        return Search(Left, mij, k);
    }
    else {
        return Search(mij + 1, Right, k);
    }
}

void solve() {
    fin >> N >> Q;
    for (int i = 1; i <= N; ++i) {
        int value; fin >> value;
        Update(i, value);
    }
    while (Q--) {
        int op, x, y;
        fin >> op;
        if (op == 0) {
            fin >> x >> y;
            Update(x, y);
        } else if (op == 1) {
            fin >> x >> y;
            fout << Query(y) - Query(x - 1) << nl;
        } else {
            fin >> x;
            fout << Search(1, N, x) << nl;
        }
    }
}

int main() {
    fin.tie(0); fout.tie(0);
    ios::sync_with_stdio(0);
    int T = 1;
//    cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}

//read the question correctly (ll vs int)
//what's the meaning of the problem ? Think outside the BOX !!!
//edge cases ?
//make it simple
//write everything (observations, edge cases, ideas, steps, methods, ...)