ARTICLE AD BOX
I’m trying to solve a problem where a robot stacks containers in a warehouse, and I want to calculate the number of operations it performs. The rules are:
There are N containers arranged in a single row.
Each container has a size Ai (1 ≤ Ai ≤ M).
The robot can pick a container and place it inside a larger container to its right.
A container that already contains another cannot be used again.
I need to count the total number of robot operations (nestings).
Input:
First line: two integers M (max container size) and N (number of containers).
Second line: N integers A1, A2, ..., AN representing the container sizes in order.
Output:
One integer: the number of robot operations performed.Example Input:
5 10 2 2 1 4 3 2 5 4 2 3Example Output:
4Explanation:
The robot nests containers into the first available larger container to its right.
After performing 4 nestings, no more containers can be nested.
What I’ve Tried:
I tried using a vector with upper_bound and lower_bound in reverse order:
for(auto it = arr.rbegin(); it != arr.rend();it++){ int val = *it; auto idx = std::upper_bound(S.begin(), S.end(), val); if (idx != S.end()) { ops++; S.erase(idx); } else { S.insert(std::lower_bound(S.begin(), S.end(), val), val); } }It works for small examples, but I’m not sure if it’s efficient enough for large N. I also read that using a multiset may be better. I'm currently getting 5/100 with this solution.
Question:
Is this approach correct and efficient?
What is the best way to implement this in C++ to handle N up to 20,000 and M up to 1,000?
