solve the following question in cpp which is given...
Creato il: 3 settembre 2025
Creato il: 3 settembre 2025
solve the following question in cpp which is given in the image , solve the given function only given in the image and make sure to verify the given example with your solution.
Below is a drop‑in implementation of scheduleRequests that runs in O(n log n) using a Fenwick tree (Binary Indexed Tree).
It builds the final queue by processing insertions from right to left: for each i, it places request[i] into the (index[i]+1)‑th empty slot.
cppvector<int> scheduleRequests(vector<int> index, vector<int> request) { int n = (int)index.size(); vector<int> ans(n); // Fenwick Tree (1-indexed) to track empty slots. vector<int> bit(n + 1, 0); auto add = [&](int i, int delta) { for (; i <= n; i += i & -i) bit[i] += delta; }; auto kth = [&](int k) { // Find smallest pos such that sum(bit[1..pos]) >= k int pos = 0; int step = 1; while ((step << 1) <= n) step <<= 1; // highest power of two <= n for (int p = step; p; p >>= 1) { int next = pos + p; if (next <= n && bit[next] < k) { k -= bit[next]; pos = next; } } return pos + 1; // 1-indexed position }; // Initially, every position is empty (value 1). for (int i = 1; i <= n; ++i) add(i, 1); // Place requests from right to left. for (int i = n - 1; i >= 0; --i) { int k = index[i] + 1; // k-th empty slot to fill int pos = kth(k); // position in 1..n ans[pos - 1] = request[i]; // store value add(pos, -1); // mark slot as filled } return ans; }
index = [0,1,2,1,2], request = [0,1,2,3,4] → [0, 3, 4, 1, 2]index=[0,1,1], request=[0,1,2] → [0, 2, 1]index=[0,0], request=[0,1] → [1, 0]index=[0,1,0], request=[0,1,2] → [2, 0, 1]This matches the step-by-step outcomes described in the problem statement.