CSES - Shared codeLink to this code:
https://cses.fi/paste/fd5bc723278d272d9edfac/
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
struct SegmentTree {
int n;
vi t;
SegmentTree(vi& a) {
n = a.size(), t.resize(4*n + 1, 0);
for(int i = 0;i<n;++i) {
update(1, 0, n - 1, i, a.at(i));
}
return;
}
void update(int v, int tl, int tr, int p, int x) {
if (tl == tr) {
t.at(v)+=x;
}
else {
int tm = (tl + tr)/2;
(p <= tm ? update(v*2, tl, tm, p, x):update(v*2 + 1, tm + 1, tr, p, x));
t.at(v) = max(t.at(v*2), t.at(v*2 + 1));
}
return;
}
int query(int v, int tl, int tr, int x) {
if (tl == tr) {
return (t.at(v) >= x ? tl:-1);
}
int tm = (tl + tr)/2;
return (t.at(v*2) >= x ? query(v*2, tl, tm, x):query(v*2 + 1, tm + 1, tr, x));
}
};
int main() {
int n, m;
cin >> n >> m;
vi a(n);
for(int& v:a) {
cin >> v;
}
SegmentTree T(a);
for(int i = 0, x;i<m;++i) {
cin >> x;
int res = T.query(1, 0, n - 1, x);
cout << res + 1 << ' ';
if (res != -1) {
T.update(1, 0, n - 1, res, -x);
}
}
cout << endl;
return 0;
}