CSES - Shared codeLink to this code:
https://cses.fi/paste/46d52021e352417e7bdd54/
#include <bits/stdc++.h>
#define range(it, a, b) for (ll it = a; it < b; it++)
#define all(x) begin(x), end(x)
#define ll long long
#define ull unsigned long long
#define INF64 ((ll) 1 << 60)
#define INF32 (1 << 30)
#define uset unordered_set
#define mset multiset
#define umap unordered_map
#define pqueue priority_queue
using namespace std;
void setio (string name) {
ios_base::sync_with_stdio(0);
cin.tie(0);
if (name.size()) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
struct MaxSegmentTree {
struct Node {
ll val, l, r;
Node* next_left;
Node* next_right;
ll get_left() { return (l + r) / 2; }
ll get_right() { return get_left() + 1; }
};
Node* root = new Node();
vector<ll>& arr;
MaxSegmentTree (vector<ll>& a) : arr(a) {
root->l = 0;
root->r = a.size() - 1;
construct_tree(root);
}
void construct_tree (Node* node) {
if (node->l == node->r) {
node->val = arr[node->l];
return;
}
node->next_left = new Node();
node->next_left->l = node->l;
node->next_left->r = node->get_left();
construct_tree(node->next_left);
node->next_right = new Node();
node->next_right->l = node->get_right();
node->next_right->r = node->r;
construct_tree(node->next_right);
node->val = max(node->next_left->val, node->next_right->val);
}
ll _get(ll l, ll r, Node* node) {
if (node->l == l && node->r == r)
return node->val;
ll r1 = (l <= node->get_left() ? _get(l, min(r, node->get_left()), node->next_left) : -INF64);
ll r2 = (r >= node->get_right() ? _get(max(l, node->get_right()), r, node->next_right) : -INF64);
return max(r1, r2);
}
ll get(ll l, ll r) { return _get(l, r, root); }
void _update (ll i, ll delta, Node* node) {
if (node->r == node->l) {
node->val = delta;
return;
}
if (i <= node->get_left())
_update(i, delta, node->next_left);
else
_update(i, delta, node->next_right);
node->val = max(node->next_left->val, node->next_right->val);
}
void update(ll i, ll delta) { _update(i, delta, root); }
};
ll n, q;
vector<ll> arr;
pair<ll, ll> bs_max(ll x, MaxSegmentTree& st) {
ll l = 0, r = n - 1, m;
ll lst;
while (l < r) {
m = (l + r) / 2;
if ((lst = st.get(0, m)) >= x) r = m;
else l = m + 1;
}
return {st.get(0, l), l};
}
void solve() {
cin >> n >> q;
arr.resize(n);
range(i, 0, n) cin >> arr[i];
MaxSegmentTree st (arr);
ll x;
pair<ll, ll> p;
while (q--) {
cin >> x;
p = bs_max(x, st);
if (p.first >= x) {
cout << p.second + 1 << ' ';
st.update(p.second, p.first - x);
}
else cout << "0 ";
}
}
int main () {
setio("");
ll t = 1;
// cin >> t;
while (t--) solve();
}