We need to understand the problem clearly.
We have n objects with sizes a_i (1-indexed). Maksim has m boxes each of capacity k. He will use the following algorithm to pack objects: He takes an empty box, then scans the objects from left to right (i.e., in order 1..n of the remaining set). For each object, if it fits in the current box (remaining capacity >= a_i), he puts it in, reducing capacity. Otherwise, if it doesn't fit, he takes a new empty box (if available) and tries again with the same object. If he has no empty boxes left and an object doesn't fit, then packing fails.
He can discard the leftmost objects (i.e., remove some prefix) to make the remaining set packable. He wants to maximize the number of objects packed (i.e., the size of the suffix that he keeps, after removing some prefix). So we need to find the largest L such that the subsequence a[L+1 ... n] can be packed using m boxes of size k with the described greedy algorithm (which is essentially the first-fit algorithm). Actually, he will keep a suffix: he throws out the leftmost object repeatedly until packing succeeds. So the answer is max possible length of suffix that is packable.
So we need to find the maximum number of objects from the end (suffix) that can be packed with m boxes of capacity k using first-fit left-to-right greedy packing.
Constraints: n, m up to 2e5, k up to 1e9, a_i up to k.
We need an O(n log n) or O(n) solution.
Observations:
The packing algorithm is deterministic: given a sequence of objects (the remaining set, in order), we simulate filling boxes one by one with objects as long as they fit. This is like the classical bin packing with First-Fit (FF) algorithm, but boxes are all of capacity k, and we have a limit m on number of boxes.
We are allowed to drop any prefix. So we want to find the longest suffix that is packable.
We can think from right to left: we want to know for each starting position i (1-indexed), whether the suffix from i to n is packable. Then answer is max length among those packable suffixes. But checking each suffix naively would be O(n^2). Need a smarter method.
We might think about the process: Given a sequence, we pack with m boxes; if it fails, we need to drop more from the left. This is reminiscent of a two-pointer (sliding window) approach: as we advance the left pointer, we include more objects from the right? Actually we are removing from left, so the suffix expands as we drop more. So we can iterate left index from n down to 1, maintaining some structure to test packability of suffix starting at left.
But the packing algorithm processes objects in order; if we keep adding objects to the front (i.e., consider earlier starting index), we need to update the packing result. That seems nontrivial.
Alternate perspective: Since the algorithm is greedy left-to-right, the failure condition depends on the prefix of the sequence. Specifically, the algorithm will succeed if and only if the number of boxes needed by the first-fit algorithm for the entire sequence is <= m. So the problem reduces to: find the longest suffix of the array such that the number of bins required by First-Fit (FF) for that suffix is <= m.
Because Maksim will pack exactly the suffix; if it fails, it means the number of bins needed exceeds m. So we need to compute FF bin count for any suffix quickly.
Now, First-Fit for bin packing (with uniform capacity) is online: we place each item into the first bin that can accommodate it, or open a new bin if none can.
Given that we have many queries (each suffix), we need a data structure to support prepending items (since as we move leftwards we add an item at the beginning of the sequence) and recompute the bin count or determine if still <= m.
But note: Adding an item at the beginning of the sequence could significantly change the assignment of all subsequent items, because the bins are used in order; early items occupy bins and affect available capacity for later items.
If we prepend an item a_i, we need to simulate its effect on the packing of the rest. The rest of the items (suffix) had some packing into bins; after adding a new item at front, the bins might be used differently: the new item will be placed into the first bin that can fit it, and that might shift the occupancy of bins for later items. This is a complex operation.
However, maybe we can use the concept of "next-fit" is simpler? But algorithm is first-fit.
But maybe there is a simpler interpretation: Since Maksim can only discard leftmost objects, the order of objects is fixed. The greedy algorithm is deterministic. So we could simulate the packing for the whole sequence and if it fails at some point (using > m boxes), we then start dropping from left until it becomes possible. The answer is the maximum number of objects that can be packed, which is essentially the size of a suffix that can be packed.
We can try to find the minimal prefix to discard such that the rest can be packed. Equivalent to find the smallest left index L (0-indexed, meaning we discard first L objects) such that suffix from L+1 to n can be packed. Then answer = n - L.
We need to find that efficiently.
Given the constraints, a binary search on L might work if we could test packability of a suffix quickly in O(n) time. Since n is up to 2e5, binary search would be O(n log n), which might be acceptable? Possibly: we can test a given suffix in O(length of suffix) by simulating first-fit. But we need to do that for O(log n) queries, total O(n log n) = 2e5 * ~18 = 3.6e6, which is fine. However, we need to simulate first-fit with up to m boxes, and we need to store bin capacities? Since m could be up to 2e5, but each simulation will process at most n items. Using a naive array for bins (like list of remaining capacities) and for each item, scanning bins from first to find one that fits would be O(m * n) in worst-case (if each item scans many bins). But we need an efficient simulation.
First-Fit can be implemented using a segment tree or Fenwick tree to quickly find the first bin with capacity >= a_i. Or we can maintain a balanced BST of bins with remaining capacities; but we need to know the first bin (by order of creation) that has enough capacity. Since bins are used in order, we need to find the earliest bin that has remaining capacity >= a_i. This is like a data structure supporting: for each bin we have remaining capacity c_j. When we insert an item of size s, we need to find the smallest index j such that c_j >= s, and then decrease c_j by s. If none, we open a new bin with capacity k-s.
We have up to m bins. For a given sequence of items (suffix), we need to simulate this online.
We can simulate with a segment tree over bins (initially empty) that stores the maximum remaining capacity in each segment. Then to find the first bin with capacity >= s, we can query the segment tree: starting from leftmost, check if max capacity in whole range is < s, then need new bin; otherwise, recursively go left to find first index. This is O(log m) per item. Since total items across all simulations in binary search could be O(n log n) = 2e5 * 18 = 3.6e6, and each item O(log m) ~ 18, total ~ 65e6 operations, which might be borderline but probably okay in C++ with optimization. However, we also need to reinitialize the segment tree for each test simulation. If we run simulation for each candidate suffix independently, we would be building a new segment tree each time, which could be heavy but still maybe okay if we allocate fresh array and build? But building segment tree each simulation O(m) which is 2e5, times 18 = 3.6e6, that's not too high. Actually building the tree (initializing capacities to k for all bins? But we may not need to pre-create all bins; we can start with 0 bins, and open new bins as needed. The segment tree could be built for up to m bins, but we only need to support dynamic number of bins. However, it's simpler: we can maintain a vector of bins, and for each item, iterate through bins to find one that fits? That would be O(m * number of items) worst-case, which is too high.
But maybe m is not huge? m up to 2e5, and suffix length could be up to n, so worst-case O(n*m) is unacceptable.
So we need an efficient simulation for each test.
Segment tree approach: we maintain an array of capacities for bins that have been opened. Initially no bins. When we need a new bin, we add it at the end with initial capacity k - s (since we place the item in it). The number of bins will be at most min(m, number of items). To support query of first bin with capacity >= s, we can use a segment tree over the current list of bins (which grows). We need to support point updates (decrease capacity of a bin) and range max queries. The segment tree can be built dynamically or we can pre-allocate size m (since we know max bins) and initially all capacities are 0 (or maybe -inf?) but we need to distinguish unopened bins. We could pre-allocate array of size m, fill with 0. When we open a new bin at index idx (starting from 0), we set its initial capacity to k - s (after placing item). But we also need to query only over opened bins. If we have unopened bins, their capacity is 0 (or maybe -inf), so they won't satisfy capacity >= s (since s >= 1). So we can query over whole range of m, but we need to stop when we exceed the current number of bins. We can maintain count of bins opened, and query only range [0, cnt-1]. That's fine; we can have segment tree over [0, m-1] with initial zeros, and as we open bins we update those positions. Query will be to find first index in [0, cnt-1] with value >= s. However, if we query entire range [0, m-1], some unopened bins have 0, and that's fine because they won't satisfy >= s. But we must ensure that the query stops at cnt-1; but if we query over the whole range, we might find an unopened bin beyond cnt-1 that still has 0 (or some leftover from previous simulation). Actually we need to reinitialize the segment tree for each simulation, so we can start with an empty tree for that simulation. To avoid reallocation, we can reuse a global structure but resetting.
Alternatively, we could avoid segment tree if we use the fact that k and a_i are integers and capacities are decreasing. However, typical approach for first-fit in bin packing is to use a segment tree.
But binary search with per-simulation O(L log m) is acceptable.
However, there's a catch: we need to test many suffixes. Binary search would require that we can test packability for any suffix quickly. But the simulation of suffix from i to n is independent. We could precompute something to answer quickly? But O(n log n) with segment tree per test might be okay.
But wait: m can be up to 2e5, but if we do binary search, we may need to simulate the whole suffix (length up to n) for each test. That would be O(n log n) per simulation? No, each simulation processes at most n items. So total work across all binary search steps is O(n log n) items processed * O(log m) per item = O(n log n log m). That's about 2e5 * 18 * 18 = 64.8 million, which is acceptable.
But we must be careful to implement efficiently in C++ (or Python? This is a Codeforces problem, likely expects C++ solution, but we can implement in Python possibly with some optimizations; but we need to produce answer. However, the problem statement seems to be from Codeforces (maybe #1485? Actually it's a known problem: "Box fitting" maybe? Not exactly). It might be solved with greedy or two-pointer.
But maybe there is a simpler O(n) solution.
Let's think about the nature of the algorithm. Maksim can only discard from the left. So the final packed objects are some suffix. When we pack a suffix, the first item of that suffix is the leftmost. The algorithm processes items left to right; it doesn't skip items. So for a suffix, the packing is exactly the first-fit on that sequence. The question: Is there a way to compute the minimal number of bins needed by first-fit for a suffix quickly as we extend to left? Possibly using some monotonic property.
Observe that if a suffix S can be packed with m boxes, then any suffix of S (i.e., dropping more left from S) can also be packed? Actually if you remove some leftmost items from S, you get a shorter suffix (starting later). That's a subsequence of the original suffix, but because it's a suffix (contiguous at the end), removing left items means you have fewer items. Usually, if you have a packable set, removing items can't increase required bins, so the number of bins needed is <= original. So if the long suffix required <= m, any shorter suffix also requires <= m. So the property "packable" is monotonic with respect to moving left index rightwards: As we increase L (discard more), the suffix becomes shorter, making it more likely to be packable. Conversely, as we decrease L (include more from left), the suffix gets longer, potentially exceeding m. So the set of L for which suffix is packable is of the form L >= L0 (i.e., we need to discard at least L0 objects). So we can binary search for minimal L (number of discarded objects) such that suffix starting at L+1 is packable. Answer = n - L_min.
Thus binary search is valid.
Now we need a checker: given starting index start (1-indexed), determine if the subsequence a[start..n] can be packed with m boxes using first-fit.
Implement first-fit efficiently: We need to maintain bins' remaining capacities. Since m up to 2e5, we can use a segment tree with max. Let's design.
Simplify: The algorithm: we have a list of bins (in order they were opened). For each item size s, we need the first bin with rem >= s. We can maintain a Fenwick tree or segment tree for range maximum and ability to find first index with value >= s. Classic approach: segment tree with binary search: query the whole range to see if max >= s; if not, open new bin. Else, we can recursively go left: if left child max >= s, go left; else go right. This gives O(log N) to find index. After placing, we update that bin (rem -= s). Opening a new bin: append to list, set rem = k - s. Number of bins can be up to m; if we exceed m, fail.
We can pre-allocate arrays of size m (or maybe m+5). For each simulation, we can have an array rem[0..m-1] initially 0, but we will set when we open a bin. But we need the segment tree to reflect the current capacities, including zeros for unopened bins, which are fine because they won't satisfy >= s (since s >=1). However, we need to be careful: when we query the whole range, we might inadvertently consider bins that are not opened yet but have zero. That's okay because they won't be chosen because max might be zero if no bin has enough capacity? But if we open bins sequentially, the opened bins are exactly indices 0..cnt-1, and unopened indices cnt..m-1 have 0. But the segment tree covering the whole array [0, m-1] will have max maybe from opened bins if any, else 0. So if we query the entire array, we might incorrectly think there is a bin with enough capacity if some unopened bin had capacity? No, unopened bins have 0 (or we could set to -1). So if no opened bin has enough capacity, max over whole array will be < s (since all opened bins have < s, unopened have 0). So condition max >= s fails, we open new bin. But we must also ensure we don't exceed m: if cnt == m and we need a new bin, fail. So the segment tree can be over full range of size m. We'll have to reset the tree for each simulation: set all values to 0 initially. Then as we open bins, we update at index cnt.
But resetting the segment tree for each simulation might be costly if we do it naively (O(m) per simulation). Since m up to 2e5 and we have O(log n) simulations, that's O(m log n) = 2e5 * 18 = 3.6e6, which is acceptable. We could also allocate a fresh segment tree each time but that's similar. Alternatively, we can maintain a global segment tree and for each simulation, we can keep track of which indices we updated and reset them after, but that's more complex. Given time constraints, O(m log n) resetting is okay.
But we also need to process up to n items per simulation, each O(log m). So total O((n + m) log n log m) roughly? Actually more precisely: For each binary search step, we run simulation O(L) items, each O(log m). Additionally we reset the segment tree O(m) (building or setting array). So per step complexity O(L log m + m). Since L can be up to n, and we have O(log n) steps, total O((n log m + m) log n). Since m can be as large as n (2e5), this is O(n log n log m + m log n). That's about 2e5 * 18 * 18 = 65M for items, plus 2e5 * 18 = 3.6M for resetting, total ~68M, which is fine.
But we must be careful in Python; 65M operations might be too slow unless optimized (with PyPy and efficient segment tree). However, many Codeforces participants solved this in C++. Since we are here to produce a solution algorithmically, we can propose a C++ solution.
But the problem could also have a simpler greedy approach using a stack or something.
Let's think deeper: The first-fit algorithm on a sequence with boxes all of size k. There is a known result: The number of bins used is equal to the number of times the cumulative sum (mod something) crosses thresholds? Not exactly.
Maybe we can transform: The algorithm is: maintain current box's remaining capacity. Actually it's first-fit, not next-fit. Next-fit would be: only check current box, if doesn't fit, close it and open new. First-fit checks all previous boxes. That's more complex.
But maybe due to the fact that we can drop only prefix, there's a trick: We can simulate the packing of the whole sequence from left to right, and if at some point we exceed m boxes, we know we need to drop some prefix. The earliest we drop, the better? Possibly we can find the minimal number of items to drop by scanning from left and using some data structure.
Alternatively, we can reverse the process: pack from right to left using last-fit? Might be easier because dropping prefix only affects early items. Could it be that the algorithm is equivalent to: The suffix is packable if and only if there exists a way to assign each item to a box among m such that the sum of sizes in each box ≤ k, respecting order? But the algorithm is fixed.
Maybe we can compute the maximum number of items that can be packed by greedily trying to pack from the rightmost items? For example, we could try to pack as many items as possible using m boxes, but the algorithm forces left-to-right. The optimal strategy to maximize number of items is to drop some prefix. That's exactly what we are doing.
Another angle: The packing algorithm is deterministic and monotonic: If we have a sequence and we prepend an item, the number of bins used cannot decrease; it may increase or stay same. And the positions of items might shift. This suggests that we can binary search.
Thus binary search with a first-fit checker is plausible.
But we need to implement the checker efficiently. Let's design the segment tree.
Implementation details for segment tree:
-
We'll have an array tree of size 4m (or 2pow2). Since m up to 2e5, 4*m is fine.
-
Initially, all leaves (capacities) are 0. Build the tree: we can either build by setting all nodes to 0, O(m). Or we can just fill the tree array with zeros, no need to build specifically, but we need to update leaves for opened bins.
-
We'll maintain cnt = number of bins opened so far, initially 0.
-
For each item size s:
-
Check if cnt == 0? Then must open new bin if m>0.
-
Else query if max over [0, cnt-1] >= s. Since segment tree covers [0, m-1], we can query [0, cnt-1] (range max). Actually we need to check only opened bins. So we call query(1, 0, m-1, 0, cnt-1). If max >= s, we need to find the first index with capacity >= s within [0, cnt-1]. We can implement a function find_first(pos, l, r, ql, qr, s) that searches for first index in [ql, qr] with value >= s. We can do: if node's max < s or segment outside query range -> return -1. Then if leaf, return index. Else recursively check left child first, then right. But we need to restrict to [ql, qr]. So we can implement a function that given node covering [l,r], and query range [ql,qr], find first index with value >= s. This is typical.
-
If found idx, we update that bin: rem = tree[idx] - s. Actually we store capacities in segment tree leaves. So we update leaf at idx: new_val = old_val - s. Then update tree upward.
-
Else (no bin found) => need to open new bin if cnt < m. Set idx = cnt. Update leaf at idx with value k - s (since new bin after placing item). Increment cnt. If cnt > m, fail (though we check before opening).
-
Continue.
At end, if we processed all items without exceeding m, return true.
Edge Cases: Could it be that an existing bin with capacity exactly 0? No, we only set capacities to positive or zero after subtraction; we might get zero. That's fine.
Complexities: For each item, we do a query to find first bin: O(log m). Actually the find_first operation is O(log m) as it traverses the tree.
But note: For each item we might also need to check if max >= s before searching? Actually find_first can return -1 if no such bin. So we can just call find_first directly on range [0, cnt-1]; if it returns -1, then open new bin. That's efficient.
Implementation details for segment tree:
We'll have an array tree that stores the maximum value in the segment. We'll implement functions:
-
build() not necessary if we set all to 0.
-
update(pos, val): set leaf at pos to val, update tree.
-
query_max(l, r) maybe not needed separately.
-
find_first(node, l, r, ql, qr, s): returns first index >= ql with value >= s, or -1.
But we need to call this for each item. Since the query range always starts at 0? Actually we are searching from first bin (index 0) up to cnt-1. So we can set ql=0, qr=cnt-1. However, as cnt grows, the range expands.
Alternatively, we can implement a simpler approach using a balanced BST (like multiset or OrderedStatisticTree) but we need to find first bin with capacity >= s in order of creation. That's like we need to maintain bins in order; we could keep a set of bins with enough capacity, but we need the first index. Could use a segment tree as above.
Another approach: use a Fenwick tree for prefix maximum? Fenwick can't easily find first index with max >= s because it's not monotonic. But we can binary search on prefix: check if max in [0, mid] >= s. That would be O(log^2 n) per item: use Fenwick for max? Fenwick supports prefix max only if we have monotonic updates? Actually Fenwick can support prefix max queries but updates are point updates decreasing the value (since we subtract). That's fine. Then we could binary search on index: find smallest idx such that prefix max >= s. That would be O(log^2 m) per item. That might still be okay: 2e5 * 18 * 18 ~ 65M. But segment tree is cleaner.
Now, we also need to be careful about resetting the segment tree between binary search steps. Since we will run multiple simulations, we could create a new segment tree for each simulation, but that would allocate memory each time. Better to allocate a global segment tree and reset it to zeros. We can have an array tree of size 4m, and we can set all values to 0 by using a fill or just when we open a bin we will update, but we also need to ensure that previous updates are cleared. Since we only update bins that we open, and we also need to clear the values of bins that were opened in previous simulation. So we could keep a list of indices we updated, and after simulation set them back to 0. But that's extra bookkeeping. Simpler: we can reinitialize the entire tree array to 0 using memset or std::fill. But tree size is 4m, which is up to 800k. 800k * 18 binary steps = ~14.4 million elements reset, which is fine.
Alternatively, we can design the segment tree to be built from scratch for each simulation using a constructor that sets all to 0. That's fine.
But note: m can be up to 200k, tree size 800k. 800k * 18 = 14.4M assignments, trivial.
Thus binary search with segment tree is doable.
But is there a more direct method? Perhaps we can compute answer by scanning from right to left using some DP. But given time, the binary search method is acceptable.
However, I recall a Codeforces problem "Maksim and the boxes" or something similar; perhaps there is a known solution using two pointers and a multiset. Let's think more.
The algorithm is: He will drop objects from left until it fits. That suggests that we can simulate the packing of the whole array while maintaining a sliding window of objects that we are considering to keep. But as we drop leftmost, we need to adjust the packing. That seems like a data structure that supports deletions from the front and queries if the current set fits. This is reminiscent of a queue where we can pop from left and we need to maintain the first-fit packing of the current queue. Could we maintain the packing state dynamically as we remove the leftmost object? That would allow a two-pointer approach: start with empty set, then add objects from right? Actually we want to find the maximum suffix length, so we can start with full array, and if it doesn't fit, we drop the leftmost and check again, but we want to do it efficiently without recomputing from scratch each time. That suggests an incremental update: when we remove the leftmost object, we need to update the packing of the remaining objects. Could be done with some undo operation? However, the removal might affect many items' bin assignments because the first item's bin might have freed capacity, causing later items to shift left into earlier bins. That's complicated.
Alternatively, we can approach from the right: start with empty set, then add objects one by one from the right (i.e., building suffix from rightmost). As we add an item to the left of the current suffix, we need to see if the packing of the new longer suffix still fits within m boxes. This is similar to the prepend operation we discussed. That could be done with a data structure that supports prepending and checking feasibility. If we could support that efficiently, we could iterate leftwards, adding a_i to the front, and stop when it no longer fits, then the answer is the length of the longest suffix we achieved. That would be O(n) times the cost of prepend. But we don't have a good data structure for prepend.
Maybe we can consider the reverse: Process items from right to left with a variant of the algorithm. Note that the algorithm is sensitive to order; if we reverse the order, it's not the same. But maybe we can think about packing from right to left with last-fit? Not directly.
Given the constraints, binary search is safe and simpler.
Now, we must also consider that the segment tree simulation might be overkill. Perhaps we can implement first-fit using a set of pairs (remaining capacity, index) sorted by capacity? But we need first index with capacity >= s, not any. The first bin in order (by creation) that fits. This is like we need to find the smallest index j such that rem[j] >= s. This is a classic problem that can be solved with a segment tree as described. Could also be solved with a "binary indexed tree of max" and then binary search on index. As mentioned, that would be O(log^2 m). That's okay.
But perhaps we can do even simpler: For each simulation, we can use a brute-force approach that is O(number_of_bins * number_of_items) but note that m may be small? m up to 2e5, so worst-case too large.
Let's test with extreme: n = 2e5, m = 2e5, all a_i = 1. Then packing any suffix will use up to min(length, ceil(total size/k)) boxes? Actually total size = length, k could be 1e9, so all items can fit in one box if k >= length? Actually a_i =1, k large. First-fit will put all items in first box because it always fits. So the number of bins = 1. So the simulation would be trivial: for each item, we check the first bin (remaining capacity huge) and place it. To find that bin quickly, we might scan bins from first; if we always use the first bin, scanning is O(1). But worst-case items might cause many bins and many checks. Consider a_i = k (large) each exactly k. Then each item requires a new bin. For each item, we scan all previous bins (which all have capacity 0) before concluding none fits, so that would be O(m^2) in worst-case if we do naive scanning. So need efficient find.
Thus segment tree needed.
Now, we should check if the binary search approach is correct with monotonic property. Indeed, if suffix of length L can be packed, any shorter suffix (by removing some leftmost items) is also packable. Because we have the same algorithm on a subset (prefix removed) — but careful: The algorithm will run on the shorter suffix. Since we have fewer items, it cannot require more bins. It could require less, but definitely not more than the original number of bins. So if original required ≤ m, shorter will also ≤ m. So monotonic.
Thus we can binary search for the leftmost index start (1-indexed) such that suffix from start to n is packable. Then answer = n - start + 1.
Implementation plan:
-
Read n, m, k.
-
Read array a (1-indexed for convenience).
-
Binary search low = 1, high = n+1? Actually we want smallest start such that packable; if none, answer maybe 0? But there is always at least one? Actually if m >= 1 and k >= min a_i, we can always pack at least the last object? Not necessarily if m=0? But m≥1. If m=0, then we can pack 0 objects. But constraints m>=1? It says 1 ≤ n, m ≤ 2e5, so m>=1. So we can always pack at least 0? Actually if m=1 and k < a_n, then the last object alone cannot fit, so we cannot pack any? But algorithm: he will take empty box, go from left to right; if the first object doesn't fit, he takes new box? But there is only one box, and if a_i > k, it doesn't fit in the empty box, then he takes new empty box? He has no more boxes, so fails. So if the last object alone is larger than k, then no object can be packed? But can he pack if he throws out all but the last object? He throws out leftmost objects until the remaining set can be packed. If the remaining set is just the last object and it's > k, then it cannot be packed because the first (and only) object doesn't fit in the box (capacity k). So pack fails. So answer could be 0. However constraints a_i ≤ k, so all objects have size ≤ k. So any single object can be packed into one box. So answer at least 1 if m>=1. Actually check example 2: n=5,m=1,k=4,a=[4,2,3,4,1]. The answer is 1 (pack only the last object). So single object of size 1 fits. So answer always >=1? If a_n ≤ k, yes. So we will have at least start = n (pack only last) packable? Let's test: with m=1, suffix of length 1 is just a_n, which is ≤ k, so packable. So start can be n. So the binary search range: start from 1 to n inclusive. We want smallest start such that suffix is packable. Since suffix of length 1 (start=n) is packable, the answer will be at least 1. Could it be that start=1 (full set) is packable? Possibly. So we can binary search.
Define function f(start): returns true if a[start..n] can be packed.
Binary search:
lo = 1, hi = n+1 (exclusive hi). We'll find first start that satisfies f(start) true. Actually we want minimal start such that true. We can do: while lo < hi: mid = (lo+hi)/2; if f(mid) true: hi = mid; else lo = mid+1. At end, start = lo. If start > n? But we know f(n) true, so start <= n. Answer = n - start + 1.
Now implement f(start). Steps:
Initialize segment tree of size m (max bins). We'll set all capacities to 0. cnt=0.
For i from start to n:
s = a[i]
if cnt == 0:
if m == 0: return false
else: open new bin with capacity k-s, cnt=1
else:
// find first bin index in [0, cnt-1] with capacity >= s
idx = find_first(1, 0, m-1, 0, cnt-1, s)
if idx != -1:
// update bin idx: new_cap = tree[idx] - s
current_cap = get_value(idx) // we can get from segment tree leaf or we can store separately; easier: we can read it from tree by a query? but we can just do update: new_val = old_val - s. To get old_val, we could store an array cap separately, or we can retrieve it via the segment tree? But the segment tree leaf holds the capacity. When we update, we need to subtract s. So we can implement an update function that does: current value at pos is stored; we can maintain a separate array rem of size m to avoid querying leaf. However, we can also implement update_sub(pos, delta) which subtracts delta from leaf. That's fine, we don't need to know old value if we just subtract. So we can do update(pos, -s) which subtracts s from leaf. But careful: our segment tree stores the actual capacity; to support subtraction we need to have the leaf value. We can have a separate array bin to store capacities, and then update the segment tree with new capacity after subtraction. But we can also update the leaf directly: we can query the leaf's current value? Without a separate array, we can implement point update that sets the leaf to a new value. But to compute new value, we need old. So it's simpler to maintain a cap array of length m, initially all 0. When we need to update bin idx: cap[idx] -= s; then call set_value(idx, cap[idx]) on segment tree. When opening new bin: cap[cnt] = k - s; set_value(cnt, cap[cnt]); cnt++. This requires a separate array, which is fine.
We also need to support find_first that uses the segment tree's max. That's fine.
Segment tree implementation: We'll build tree of size 4m, and we have a function build that sets all to 0. But we can just fill tree array with zeros at start of each f call (e.g., using vector tree(4m, 0) inside f). However, we also need cap array; we can also allocate new each time, but that would be O(m) allocation per call. That's okay (2e5 * 18 = 3.6M allocations? Might be heavy but okay in C++ with vector reallocation? Better to allocate once globally and reset. We'll design globally.
We can define global arrays: vector<long long> cap; but size m, we need to set to 0 each f call. We can use vector<long long> cap(m, 0) inside f? That would allocate fresh each call, which might be okay but might cause memory churn. However, since we call f O(log n) times (max 18), it's fine. But we also need tree: vector<long long> tree(4*m);. Both allocated per call.
Given m up to 2e5, 4m = 800k, times 18 = 14.4M elements, which is ~115 MB if each is 8 bytes, that's a lot but not necessarily if allocated sequentially and freed. Actually each allocation of 800k long longs is 6.4 MB (since 8 bytes * 800k = 6.4 MB). 6.4 MB * 18 = 115 MB if all simultaneously alive, but they won't be; each call will allocate and deallocate. However, stack/ heap management might be okay. But to be safe, we can allocate global arrays of size m (or 4m) and reuse them by resetting only needed portions. But simpler: allocate inside function; it should be fine for CF if we use 64-bit ints.
But careful: k up to 1e9, a_i up to 1e9, capacities can be up to 1e9, so we need 64-bit (long long) to avoid overflow when subtracting.
Now, find_first implementation: We'll implement a recursive function that takes node index, segment l,r, query range ql,qr, and value s. It returns the first index in that range where value >= s, or -1.
Pseudo:
int find_first(int node, int l, int r, int ql, int qr, long long s) {
if (r < ql || l > qr || tree[node] < s) return -1;
if (l == r) return l;
int mid = (l+r)/2;
int left_res = find_first(node2, l, mid, ql, qr, s);
if (left_res != -1) return left_res;
return find_first(node2+1, mid+1, r, ql, qr, s);
}
But we must ensure that we restrict to the query range. The early condition if (r < ql || l > qr || tree[node] < s) return -1; works because if segment is completely outside query range, skip; also if max in segment < s, skip. Then if leaf, return. Else search left first, then right.
This works as long as tree[node] stores the max in that segment.
Note: Since we are querying [0, cnt-1] and the tree may have zeros for indices >= cnt, but those indices are outside query range, so they are excluded by range condition. Good.
Now update function: point update.
void update(int node, int l, int r, int pos, long long val) {
if (l == r) {
tree[node] = val;
return;
}
int mid = (l+r)/2;
if (pos <= mid) update(node2, l, mid, pos, val);
else update(node2+1, mid+1, r, pos, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
We'll set the value, not add.
Now we also need get leaf value maybe? Not needed.
Simulation:
bool can(int start) {
int cnt = 0;
// initialize segment tree and cap array
vector cap(m, 0); // capacities of bins
// build segment tree: initially all zeros. We'll create tree as vector tree(4m, 0);
// But we need to access m. m is global.
// We'll define tree locally.
vector tree(4m, 0);
// Actually we need to pass tree to functions; we can make them lambdas capturing by reference.
// Or we can implement a class SegmentTree and instantiate.
// For simplicity, we can implement a class inside main or as struct.
// Let's design a struct.
}
But we need to implement the segment tree operations with the local tree. I'll define a struct that holds tree and size, with methods: update, query_max (maybe not needed), find_first.
But find_first requires recursion; we can implement iterative? Recursion depth log m ~ 18, fine.
We'll implement a class:
class SegTree {
public:
int n;
vector tree;
SegTree(int size) {
n = size;
tree.assign(4n, 0);
}
void update(int pos, long long val) {
update(1, 0, n-1, pos, val);
}
int find_first(int ql, int qr, long long s) {
return find_first(1, 0, n-1, ql, qr, s);
}
private:
void update(int node, int l, int r, int pos, long long val) {
if (l == r) {
tree[node] = val;
return;
}
int mid = (l+r)/2;
if (pos <= mid) update(node2, l, mid, pos, val);
else update(node2+1, mid+1, r, pos, val);
tree[node] = max(tree[node2], tree[node2+1]);
}
int find_first(int node, int l, int r, int ql, int qr, long long s) {
if (r < ql || l > qr || tree[node] < s) return -1;
if (l == r) return l;
int mid = (l+r)/2;
int left_res = find_first(node2, l, mid, ql, qr, s);
if (left_res != -1) return left_res;
return find_first(node*2+1, mid+1, r, ql, qr, s);
}
};
But careful: The find_first as written will check the entire segment even if part of it is outside ql,qr? The first condition if (r < ql || l > qr || tree[node] < s) return -1; ensures that if the segment is entirely outside or max < s, we skip. If the segment partially overlaps but max >= s, we go deeper. That's correct.
Now simulation:
SegTree seg(m);
vector cap(m, 0); // we might not need cap if we can retrieve from seg? But we need to compute new capacity when updating. We can use seg to get current value? We could have a method long long get(int pos) but we don't have. We could store cap separately, or we can maintain a separate array rem to know current capacity for each bin, to compute new capacity after subtraction. Since we update seg with new value, we need old value. So we can store rem array.
Simplify: Let's have rem vector of length m, initially all 0. When we update a bin, we do: rem[idx] -= s; seg.update(idx, rem[idx]);
When opening new bin: idx = cnt; rem[idx] = k - s; seg.update(idx, rem[idx]); cnt++;
Now process each item:
s = a[i];
if (cnt == 0) {
if (m == 0) return false; // but m>=1
// open new bin
if (cnt >= m) return false; // but cnt=0, m>0, so okay.
rem[cnt] = k - s;
seg.update(cnt, rem[cnt]);
cnt++;
} else {
// find first bin
int idx = seg.find_first(0, cnt-1, s);
if (idx != -1) {
rem[idx] -= s;
seg.update(idx, rem[idx]);
} else {
// need new bin
if (cnt >= m) return false;
rem[cnt] = k - s;
seg.update(cnt, rem[cnt]);
cnt++;
}
}
Continue.
After loop, return true.
That's the checker.
Now complexity per item: find_first O(log m), update O(log m). So O(2 log m) per item.
Now overall binary search: O(n log n log m). With n=2e5, log n18, log m18, total ~ 65M operations times constant. Should be fine in C++.
But we need to be careful: In the worst-case, each item may cause a new bin (when a_i large). Then cnt increases, and each find_first will query over increasingly large range, but still O(log m). So fine.
Now, is there any scenario where m is very small, say m=1? Then the segment tree size is 1. The operations still fine.
We need to ensure that we don't allocate huge vectors inside the checker many times, as that would be costly. But we can allocate once globally and reuse.
Better: Write a function bool check(int start) that uses global arrays rem and seg that are allocated once with size m and reset appropriately. However, resetting the segment tree to all zeros and rem to zeros for the entire array each call can be O(m). That's okay. We can just fill rem with zeros and rebuild seg tree? We could also rebuild the seg tree by setting all nodes to zero; but we can also just update only the bins we use and after the call set them back to zero. But the O(m) reset is acceptable.
But we can improve: Instead of resetting the whole seg tree (4m) which is O(m), we can reinitialize the tree by creating a new SegTree object inside check; that will allocate and fill with zeros in constructor (since we assign vector(4n, 0) which is O(m) anyway). So both are O(m). That's fine.
Given m <= 2e5 and log n <= 18, total reset cost = 3.6 million assignments, trivial.
So we can just create a new SegTree and rem vector inside each check.
Now, the only issue is that constructing a vector of size 4*m (800k) 18 times might allocate and deallocate memory repeatedly, which could be a bit slower but still should pass within 1-2 seconds in C++. Many Codeforces solutions do similar.
Alternatively, we can pre-allocate globally and use a versioning technique, but not needed.
Let's test on examples.
Example 1: n=5, m=2, k=6, a=[5,2,1,4,2]. Binary search: find smallest start. check start=3? Actually need to test. But we trust.
But there is nuance: The algorithm description says: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." This is exactly first-fit: he always uses the first box that fits, starting from the first box? Actually, the description: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." This could be interpreted as: He starts with one empty box (the current box). For each object, if it fits in the current box, he puts it there. If it doesn't fit, he takes a new empty box and makes it the current box, then puts the object? But the phrase "continues the process above" suggests after taking a new box, he continues with the same object? Actually typical bin packing algorithm: he has a set of boxes, initially all empty. He picks an empty box, then goes through objects. But the description might be ambiguous. Let's read carefully:
"He takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above."
I think the intended algorithm is: He starts with an empty box (current box). For each object in order, he checks if it fits in the current box; if yes, he puts it in and updates remaining capacity. If it does not fit, he takes a new empty box (if any left), makes it the current box, and then puts the object in that new box (since it must fit because a_i ≤ k, and new box has capacity k). Then he continues with the next object, still using the same current box (which is the last box he used). That is actually the Next-Fit algorithm, not First-Fit! Wait, let's parse: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above."
The key is "current box". He starts with one box. For each object, if it fits, he puts it. If not, he takes a new empty box. Does he then check the object again? The phrase "and continues the process above" implies he goes back to the beginning? Actually, "continues the process above" likely means that after taking a new empty box, he then considers the same object again? Or continues with the next object? Typically, in many descriptions of such packing algorithms, this is the Next-Fit: you have a current open box; if the item fits, you put it; otherwise, you close that box and open a new one for the item. The phrase "takes the new empty box and continues the process above" might mean that after opening a new box, he goes back to the step "if the i-th object fits in the current box" — so he checks the same object with the new box. Since a_i ≤ k, it will fit, so he puts it. Then for the next objects, the current box is this new box.
This is exactly Next-Fit, not First-Fit. However, the note in the first example says: Distribution of objects will be [5], [2, 1]. Let's simulate with Next-Fit on the full array [5,2,1,4,2] with m=2, k=6:
- Start with box1 (empty, cap 6). Object1 size5 fits -> put, remaining cap1.
- Object2 size2: does it fit in current box (box1)? remaining cap1 < 2, so does not fit. So take new empty box2, then put object2 into box2? After taking new box, we put object2 into it (since it fits). So box2 now has cap4 (6-2). Current box becomes box2.
- Object3 size1: check current box (box2): remaining cap4 >=1, so put -> box2 cap3.
- Object4 size4: check current box (box2): cap3 <4, so does not fit. Need new box, but no boxes left (m=2, already used 2 boxes). So cannot pack object4. So distribution would be [5] and [2,1]. That matches the example. So indeed it is Next-Fit, not First-Fit.
Then example 2: n=5, m=1, k=4, a=[4,2,3,4,1]. With Next-Fit, packing all: box1: object1 size4 fits, cap0. Object2 size2: does not fit (cap0), need new box, but no boxes left -> fail. So cannot pack all. If he discards leftmost objects, he can pack only the last object: [1] fits. That matches. Example 3: n=5, m=3, k=3, a=[1,2,3,1,1]. Next-Fit simulation: box1:1->cap2, 2 fits? cap2 >=2 -> put, cap0. 3: does not fit cap0 -> open box2, put 3, cap0. 4: size1 does not fit box2 cap0 -> open box3, put 1, cap2. 5: size1 fits box3 cap2 -> put, cap1. So distribution: [1,2], [3], [1,1] -> matches example. So indeed the algorithm is Next-Fit (NF) not First-Fit.
So I misinterpreted earlier. The algorithm is Next-Fit: only the current box is considered; if the item doesn't fit, open a new box and put the item there (and that becomes current). There is no looking back at earlier boxes. The description says "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box ... Otherwise he takes the new empty box and continues the process above." This is ambiguous but the examples confirm it's Next-Fit.
Therefore the problem is simpler! Because Next-Fit is much easier to simulate and analyze. Indeed, Next-Fit is an online algorithm that only keeps the most recent box open. That's why the examples had that pattern.
So we can simplify drastically.
Now the problem reduces to: Given the sequence, and m boxes of capacity k, using Next-Fit algorithm (which only uses the current box and opens a new one when the current cannot fit the next item), what is the maximum length of a suffix that can be packed? (after discarding some prefix).
Since Next-Fit is simple: we just iterate through the items in order, maintaining remaining capacity of the current box; if the item fits, we put it and reduce capacity; else we open a new box (if any left) and put the item there. If we run out of boxes, packing fails.
Thus the simulation for a given suffix is O(length) and doesn't need any data structure besides a variable for current remaining capacity and a counter for used boxes.
Wait, but is that correct? Next-Fit does not consider previous boxes at all. So the state is just: current box's remaining capacity, and number of boxes used so far (including current). That's it.
But careful: In Next-Fit, when you open a new box for an item that doesn't fit, you close the previous box and never use it again. So the algorithm is: start with box count = 1, current remaining = k. For each item: if item size <= current remaining, put it, current remaining -= size; else, if box count < m, increment box count, set current remaining = k - size; else fail.
That's all. So simulation is O(L) per suffix.
Thus we can binary search with a checker that runs in O(L) time, total O(n log n). That's definitely acceptable and much simpler.
But is there any nuance? The problem statement says "he takes one of the empty boxes he has" maybe implying he could choose any empty box? But the algorithm described and examples show Next-Fit. Actually, let's re-read: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." The phrase "current box" suggests he has a current box. The phrase "takes the new empty box" implies that when the item doesn't fit, he gets a new box, presumably becomes the current one. So indeed it's Next-Fit.
Thus we can implement the checker in O(L) time.
Now we can do binary search as before.
But maybe we can do even better: Since the simulation is linear, we could use a two-pointer sliding window approach: start with full array, simulate Next-Fit, if fails at some point, we need to drop the leftmost object. But we can update the state efficiently when dropping the leftmost? Possibly we can use a prefix-sum-like approach? Let's think.
Next-Fit is not easily reversible because the state depends on the entire prefix. However, we can simply binary search.
Given n up to 2e5, O(n log n) is fine: 2e5 * 18 = 3.6e6 operations, trivial.
We should also consider that the checker for a suffix can be done from start to n, but we could also precompute something to answer faster? Not needed.
But be careful: The algorithm as described may also involve that when he starts, he "takes one of the empty boxes he has" — he has m boxes initially all empty. He takes one empty box to start. That's equivalent to having current box = first box.
Yes.
Now implement check(start):
used = 1 // number of boxes used so far, starting with first box
rem = k // remaining capacity of current box
for i from start to n:
if a[i] <= rem:
rem -= a[i]
else:
used += 1
if used > m: return false
rem = k - a[i] // after placing item in new box
return true
But careful: When we open a new box, we put the current item in it. So rem = k - a[i]. That's correct.
Edge: The first item might be > k? But a_i ≤ k, so it fits.
Now test with examples:
Example 1: n=5,m=2,k=6,a=[5,2,1,4,2]. Check start=1 (full): used=1,rem=6; i=1:5<=6 -> rem=1; i=2:2>1 -> used=2,rem=6-2=4; i=3:1<=4->rem=3; i=4:4>3 -> used would become 3 >2 => false. So full not packable. Check start=2: suffix [2,1,4,2] -> used=1,rem=6; i=2:2<=6->rem=4; i=3:1<=4->rem=3; i=4:4>3->used=2,rem=6-4=2; i=5:2<=2->rem=0; success, used=2 <=2. So suffix from 2 works. That would give answer 4? n - start +1 = 5-2+1=4. But the example answer is 4 and they said they throw out first object, so start=2 indeed. But wait, the example says they throw out the first object (5) and then distribution is [2,1], [4,2]. That matches. So our check(start=2) returns true. Also check(start=1) false. So minimal start =2, answer=4.
But could start=1 be packable with some other choice? No.
Example 2: n=5,m=1,k=4,a=[4,2,3,4,1]. Check start=5: [1] -> used=1,rem=4; i=5:1<=4->rem=3; success, used=1. So true. start=4: [4,1] -> used=1,rem=4; i=4:4<=4->rem=0; i=5:1>0->used would become 2 >1 -> false. So start=4 false. So minimal start=5, answer=1. Correct.
Example 3: n=5,m=3,k=3,a=[1,2,3,1,1]. Check start=1: used=1,rem=3; i1:1->rem=2; i2:2<=2->rem=0; i3:3>0->used=2,rem=0? Actually after opening new box for i3: rem = 3-3=0; i4:1>0->used=3,rem=3-1=2; i5:1<=2->rem=1; used=3 <=3, success. So true. So minimal start=1, answer=5.
Thus binary search works.
Now complexity: O(n log n). That's trivial.
But wait, there is a catch: The algorithm states: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." There is a nuance: When he takes a new empty box, does he also consider that he might have multiple empty boxes and he could choose any? The phrase "takes the new empty box" suggests he takes a fresh box from the pool, not any previously opened but closed? Since it's Next-Fit, we only use the most recent. The examples confirm.
Thus our simulation is correct.
Now we should also consider: Might there be an even simpler O(n) solution? Possibly using two-pointer: we can simulate the packing from left to right on the whole array while maintaining a window of objects we are considering to keep, but we can also compute the answer by scanning from left and right? But binary search is simple enough.
However, we must be careful about the monotonic property: Is it true that if a suffix is packable, then any shorter suffix (starting later) is also packable? For Next-Fit, yes, because fewer items cannot require more boxes. Actually, is it possible that removing an item could increase the number of boxes needed? No, because you are removing an item, the algorithm will process fewer items, so number of boxes used is non-increasing. So the property holds.
Thus binary search is correct.
Implementation details:
We'll store a in vector or long long? a_i up to 1e9, but we can store int if within 2^31? 1e9 fits in 32-bit signed int. k up to 1e9, also fits. However, when we subtract, rem could be up to 1e9, so int is fine. But used boxes count up to m, int is fine.
But we need to be careful about overflow when doing k - a_i? k up to 1e9, a_i up to 1e9, k-a_i could be 0 or positive, fits in int.
So we can use int.
Now, the binary search:
int lo = 1, hi = n; // we want smallest start that works.
while (lo < hi) {
int mid = (lo + hi) / 2;
if (check(mid)) hi = mid;
else lo = mid + 1;
}
// after loop, lo is smallest start such that check true.
int ans = n - lo + 1;
cout << ans << endl;
But we need to ensure that for start = n, check is true (since a_n ≤ k). So the binary search will converge to some start <= n.
Edge case: It might be that even the suffix of length 1 (last object) is not packable? But a_n ≤ k, so it fits in a single box, so packable. So always at least one.
But what if m = 0? The problem says 1 ≤ m, so no.
Thus done.
Now, check function implementation O(n). However, note that we will call check about log2(200k) ≈ 18 times, each time scanning up to n items. That's about 3.6 million iterations, which is very fast.
We could even do a linear scan from left to right to find the minimal start directly: start from full, simulate packing, if fails at some point, we need to drop the first object, but we might be able to skip more? Not trivial. Binary search is fine.
But there is a nuance: The Next-Fit algorithm as described might have a subtlety: when he takes a new empty box, does he also consider the possibility that there are other empty boxes from earlier that are not current? The phrase "takes the new empty box" suggests he opens a new one, not reuses an old one. So it's Next-Fit.
Thus final solution: binary search + Next-Fit simulation.
Now, we should also test some edge cases:
Case: m=2, k=5, a = [5,1,5]. Full simulation: used=1,rem=5; i1:5 fits rem=0; i2:1>0 => used=2, rem=5-1=4; i3:5>4 => used would be 3>2, fail. So not packable. Suffix starting at 2: [1,5] => used=1,rem=5; i2:1 fits rem=4; i3:5>4? used=2, rem=5-5=0; success used=2. So answer=2. Binary search would find start=2.
Case: m=1, k=3, a=[2,2]. Full: used=1,rem=3; i1:2 -> rem=1; i2:2>1 -> need new box but m=1, fail. Suffix start=2: [2] works. So answer=1.
Case: m=2, k=10, a=[6,5,5]. Full: used=1,rem=10; i1:6->rem=4; i2:5>4->used=2, rem=10-5=5; i3:5 fits rem=0; success used=2. So answer=3.
All good.
Now, is there any scenario where the algorithm behaves differently because of the phrase "he takes one of the empty boxes he has"? Could he choose which empty box to start with? At the beginning, he takes one empty box (presumably any, but all are identical). So it's fine.
Now, we should double-check the note: In the first example, the distribution after throwing out first object is [2,1], [4,2]. That matches Next-Fit: start with [2,1] in first box, then [4,2] in second. Actually Next-Fit would give: start box1: 2 -> rem=4, 1 -> rem=3; then 4 doesn't fit -> open box2: 4 -> rem=2, then 2 fits -> rem=0. So distribution [2,1] and [4,2] indeed. So correct.
Thus solution is straightforward.
Given the simplicity, we can even do a linear scan from right to left, maintaining the state of packing from that point? But that would be more complex.
Let's see if we can do O(n) by scanning from right to left with some precomputation. For Next-Fit, the packing from a given start is easy to compute. The number of boxes needed for a suffix is monotonic with start: as start increases (shorter suffix), the number of boxes needed is non-increasing. So we could compute the number of boxes needed for each suffix via some DP? Since Next-Fit is a simple greedy, we can compute the number of boxes needed for the entire array in O(n). But for each suffix we could compute using a backward DP: let f[i] = number of boxes needed to pack a[i..n] using Next-Fit. Is there a recurrence? Next-Fit processes left to right, so if we know the state after packing a[i..n], it depends on the entire suffix. Not easily derived from f[i+1] alone because the first box's remaining capacity after packing a[i..n] influences the packing of a[i]. Actually we could compute from left to right and record the state at each position, then maybe use two pointers? But binary search is simpler.
Thus final answer: implement binary search with Next-Fit checker.
Now we need to produce the solution in C++. Let's draft code.
Pseudo:
#include <bits/stdc++.h>
using namespace std;
int n, m, k;
vector a;
bool check(int start) {
int used = 1;
int rem = k;
for (int i = start; i < n; ++i) { // 0-indexed? We'll use 0-indexed.
if (a[i] <= rem) {
rem -= a[i];
} else {
++used;
if (used > m) return false;
rem = k - a[i];
}
}
return true;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0);
cin >> n >> m >> k;
a.resize(n);
for (int i = 0; i < n; ++i) cin >> a[i];
// binary search on start index (0-indexed) smallest such that check(start) true.
int lo = 0, hi = n; // hi exclusive? We want smallest index that works. Since check(n-1) true (last element), lo will be <= n-1.
// We'll use [lo, hi) range: lo=0, hi=n. Invariant: check(hi) is true? Actually check(n) (out of bounds) would be empty suffix, which is trivially packable? But we don't need that. We know at least n-1 works.
// Let's set hi = n (means we consider empty suffix as true) and binary search for first true from right? Easier: while (lo < hi) { mid = (lo+hi)/2; if (check(mid)) hi = mid; else lo = mid+1; } After, lo is smallest index with check true.
// But need to ensure check(n) is true (empty suffix). Since empty suffix uses 0 boxes? But our check function expects start index within [0, n-1]. If start == n, there are no objects; trivially packable. We could handle that by initial hi = n, and if mid == n, treat as true. But we can also set hi = n-1 and after binary search adjust. Simpler: binary search on the length of discarded prefix? Let's think.
// We'll search for the first start index such that suffix is packable. Since check(n-1) is true, we can set hi = n-1? But then if check(mid) true, we set hi = mid; else lo = mid+1. Starting lo=0, hi=n-1 inclusive? We'll use while (lo < hi): mid = (lo+hi)/2; if check(mid) then hi = mid else lo = mid+1. At the end lo == hi, and it's the smallest index with check true. This works if we guarantee that hi (initial) is true. So we need to set hi to some index that is known true. n-1 is true. So set hi = n-1.
// But what if n=0? not possible.
// But check(n-1) is always true? a[n-1] <= k, so with one box it fits, so true.
// So code:
int lo = 0, hi = n-1;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (check(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
int ans = n - lo; // because lo is 0-indexed start, number of objects = n - lo
cout << ans << endl;
return 0;
}
But we need to ensure check(mid) uses correct indices. Our a is 0-indexed, so start = mid means we consider objects from mid to n-1. Good.
Let's test with examples:
Example 1: n=5, a indices 0..4: [5,2,1,4,2]. check(0) false. check(1) true. So lo=0, hi=4. mid=2? Actually binary search: lo=0, hi=4. mid=2. check(2)? suffix [1,4,2] simulation: used=1,rem=6; 1->rem=5; 4 fits? 4<=5 -> rem=1; 2>1 -> need new box, used=2, rem=6-2=4; done used=2 -> true. So check(2) true, hi=2. lo=0, hi=2, mid=1. check(1) true, hi=1. lo=0, hi=1, mid=0. check(0) false, lo=1. loop ends lo=1. ans = 5-1=4. correct.
Example 2: n=5, a=[4,2,3,4,1]. check(4) true (suffix [1]). check(3) false. So binary search: lo=0, hi=4. mid=2. check(2)?? suffix [3,4,1]. Simulate: used=1,rem=4; 3 fits rem=1; 4>1 -> used=2 >1? m=1, so used becomes 2 >1 -> false. So check(2) false -> lo=3. lo=3, hi=4, mid=3. check(3) false -> lo=4. ans =5-4=1. correct.
Example 3: n=5, a=[1,2,3,1,1]. check(0) true, so binary search should find lo=0? Let's see: lo=0, hi=4. mid=2. check(2) true? suffix [3,1,1] with m=3,k=3: used=1,rem=3; 3 fits rem=0; 1>0 -> used=2, rem=2; 1 fits rem=1; used=2 <=3 -> true. So hi=2. lo=0, hi=2, mid=1. check(1) true? suffix [2,3,1,1]: used=1,rem=3; 2 fits rem=1; 3>1 -> used=2, rem=0; 1>0 -> used=3, rem=2; 1 fits rem=1; used=3 <=3 true. So hi=1. lo=0, hi=1, mid=0. check(0) true, hi=0. lo=0. ans=5. correct.
Works.
Now we must consider edge case: if check(0) is true, binary search will set lo=0 correctly.
Complexity: O(n log n). Should be fine.
Potential improvement: Since check is O(n) and we call it log n times, we might want to early exit if we exceed m. That's already done.
One nuance: In the check, when we open a new box, we set rem = k - a[i]. This is correct because we place the item immediately. Also, we start with used = 1 and rem = k. This assumes we have at least one box. Since m>=1, it's fine. But what if m==0? Then we cannot pack any object. But constraints m>=1, so ignore.
Now, let's double-check the problem statement: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." This description could also be interpreted as: He picks an empty box (any) to start, and then for each object, if it fits in the current box, he puts it; otherwise, he picks a new empty box (any empty box, not necessarily fresh from the pool?) but then "continues the process above" might mean he goes back to the beginning of the object list? Actually no. The examples clearly show Next-Fit.
Thus we are good.
Now, we should consider if there is any scenario where the algorithm would behave like First-Fit if he could choose any empty box from the set when the current doesn't fit? The phrase "takes the new empty box" suggests it's a new one, not previously opened but emptied? So it's Next-Fit.
Thus solution stands.
But wait, the phrase "takes the new empty box" might also be interpreted as: if the current box doesn't fit, he takes another empty box from the ones he already has (which are initially all empty), meaning he could choose any empty box, not necessarily a brand new one. However, since all boxes are empty initially, and he hasn't used them yet, any empty box is essentially new. But after some boxes are used, they are not empty. So the only empty boxes are those not yet used. So "new empty box" means a box that hasn't been used before, i.e., a fresh box. So he's not allowed to go back to a previously opened but partially filled box; he only considers the current box, and if it doesn't fit, he opens a fresh box. So it's Next-Fit.
Thus final answer: binary search + Next-Fit simulation.
Given the simplicity, we can implement in C++.
Now, note that we could also compute answer by scanning from rightmost and counting boxes needed, but binary search is straightforward.
Potential pitfalls: None.
Now, let's write final code.
We'll use 0-indexing.
Check function:
bool check(int start) {
int used = 1;
int cur = k;
for (int i = start; i < n; ++i) {
if (a[i] <= cur) {
cur -= a[i];
} else {
++used;
if (used > m) return false;
cur = k - a[i];
}
}
return true;
}
But need to handle case when start == n? Not called because hi = n-1.
Now, if m is very large, used could overflow? used up to n (2e5) fits int.
Now, we should consider if k could be smaller than some a_i? Constraint says a_i ≤ k, so always fits in a fresh box.
Thus solution is done.
But wait, is it really that simple? Let's double-check the problem statement again: "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." The phrase "new empty box" could be interpreted as "another empty box from the set he already has", but that would be the same as "any empty box". In the context of the algorithm, he initially has m empty boxes. He picks one empty box (call it current). Then he goes through objects. If an object doesn't fit in the current box, he picks another empty box from his set (if any), which becomes the current box, and then he continues. That is indeed Next-Fit? Actually Next-Fit is defined as: you have a current bin; if the item fits, you put it; else, you open a new bin and make it current. The key is you never go back to previous bins. In this interpretation, he picks another empty box from the set, which could be any empty box, but since all empty boxes are identical and he just picks one, it's essentially opening a new one (the next empty). There's no advantage to picking a specific empty box because they're all empty; but if he could also pick a box that was used before but is now empty? However, boxes are only used once; they are not emptied. So all boxes that haven't been used are empty. So picking any empty box is like opening a new one. So it's Next-Fit.
Thus all good.
Now, final answer: produce code.
But before finalizing, let's test with some random cases and compare with a brute-force for small n to ensure correctness. We'll do mental.
Case: n=4,m=2,k=5,a=[2,3,2,2]. Full: used=1,rem=5; 2->rem=3; 3 fits? rem=3>=3 -> rem=0; 2>0 -> used=2, rem=5-2=3; 2 fits rem=1; done used=2. So packable, answer=4. Our binary search: check(0) true -> lo=0 ans=4.
Case: n=4,m=2,k=5,a=[2,3,2,3]. Full: 2->rem=3;3 fits rem=0;2>0 -> used=2,rem=5-2=3;3 fits rem=0; used=2 success. Answer=4.
Case: n=4,m=2,k=5,a=[2,4,2,2]. Full: 2->rem=3;4>3 -> used=2,rem=1? Actually after opening new box for 4: rem=5-4=1; then 2>1 -> used would become 3 >2 fail. So not packable. Suffix start=1: [4,2,2] -> used=1,rem=5; 4 fits rem=1; 2>1 -> used=2,rem=5-2=3; 2 fits rem=1; used=2 success. So answer=3. Binary search should find start=1.
Edge: m=1, all items must fit in one box. So the longest suffix that has total sum ≤ k? Not exactly, because Next-Fit with one box just checks if each item fits sequentially, but if total sum ≤ k, it's fine because each item will fit as long as at each step remaining >= item size. But if total sum ≤ k, it's fine; but if total sum > k, maybe still fine if the items are placed in order? Actually with one box, you start with capacity k, and you subtract each item as long as it fits. If at any point an item doesn't fit, you would need a new box but can't, so fails. So the condition for a suffix to be packable with one box is that the sum of all items ≤ k? Not necessarily: if the items are in order, you subtract sequentially; if at some point remaining capacity becomes less than the next item, it fails even if total sum ≤ k? Example: k=5, items [3,3]. Total sum 6>5, fails. But total sum ≤ k is necessary but not sufficient? Actually with one box, you can only put items as long as they fit. Since items are processed in order, the condition for success is that the prefix sum never exceeds k? That is, the cumulative sum of items from start to any point ≤ k. Because you start with k, after each item remaining = k - cumulative sum. So need cumulative sum ≤ k at all steps. That's equivalent to max prefix sum ≤ k. So for m=1, the condition is that the maximum prefix sum (of the suffix) ≤ k. That's stronger than total sum ≤ k. Example: k=10, items [6,5]. Total sum 11>10, fails. But also max prefix sum = 11? Actually prefix sum after first =6 ≤10, after second =11>10, fails. So condition is exactly cumulative sum never exceeds k. This is consistent with Next-Fit algorithm.
Our simulation for m=1 will correctly enforce that.
Now, is there any scenario where Next-Fit behaves differently from First-Fit and would cause the answer to be not simply the longest suffix that can be Next-Fit packed? That's exactly what the problem asks: he uses that algorithm. So yes.
Thus solution accepted.
But wait, the problem says: "Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." There is a nuance: "takes the new empty box" might be interpreted as "takes a new empty box (i.e., not the current one) and continues the process above" meaning after taking the new empty box, he goes back to the beginning of the object list? That would be weird. Usually, "continues the process above" means he goes back to the step of checking if the object fits in the current box (which is now the new box). So it's as we used.
Thus our solution is correct.
Now, given the simplicity, the problem likely expects an O(n) solution using two pointers (sliding window) because binary search is too straightforward? But O(n log n) is fine for constraints. However, there might be a trick to do O(n) by scanning from left to right and maintaining some pointer for the leftmost discard.
Let's think about an O(n) approach: Because the algorithm is Next-Fit, we can simulate packing of the whole array, and whenever we run out of boxes (i.e., need more than m), we need to drop the leftmost object(s). However, dropping the leftmost object might affect the packing of the remaining objects, but perhaps we can adjust the simulation incrementally.
Consider we maintain a queue of objects that we are currently trying to pack. Initially, we try to pack the whole array. We simulate Next-Fit from left to right, keeping track of the state (current box remaining, used boxes count) as we process items. If we reach a point where we need an (m+1)-th box, we know the current set (starting from some left index) cannot be packed. We then need to drop the leftmost object. But after dropping the leftmost object, the packing of the rest might change because the first object removed might have been in some box, and its removal could free up capacity that could allow later items to fit better, possibly reducing the number of boxes needed. However, note that with Next-Fit, the packing is deterministic and depends on the order. If we remove the first object, the rest of the sequence shifts left, and we need to repack from the new first object. This might result in a different assignment of items to boxes. To compute the new packing efficiently, we could start simulation from the new left index, which would be O(n) per removal, leading to O(n^2) worst-case.
But we can use two pointers: keep a right pointer that expands the suffix as we move left? Actually we want the longest suffix that works. That is essentially find the smallest start index such that suffix works. This can be found by scanning from left to right while maintaining some state? Not straightforward.
But we can use the following: Since Next-Fit is online, the number of boxes needed for a suffix can be computed in O(length). So binary search is simplest.
Given the constraints, O(n log n) is acceptable, and the code is short.
Thus final solution: binary search with linear check.
Let's also consider if we can do binary search on answer (the number of objects) directly: we can check if there exists a suffix of length L that is packable. But we need to check all possible suffixes of length L; that's O(n) per check if we slide window? Not directly. Binary search on start index is easier.
Implementation details:
-
Use fast I/O.
-
Use long long for capacities? int works because k and a_i up to 1e9, subtraction yields non-negative up to 1e9, fits in int (2^31-1). But sum of many items may exceed 2e9? For used boxes, we only care about remaining capacity of current box, which is at most k (1e9). So int is safe.
-
But in check we do cur -= a[i]; if a[i] and cur are int, fine.
Now, one more nuance: The algorithm says: "if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." It doesn't explicitly say that after taking a new empty box, he puts the object into it. But the example confirms that's the case. Also logical.
Thus code.
Now, I'll produce final answer in C++.
But before finalizing, let's ensure the checker is correct for all cases. Let's test a tricky case: m=2, k=10, a=[9,2,9]. Full: used=1,rem=10; 9 fits rem=1; 2>1 -> used=2, rem=10-2=8; 9>8 -> would need third box -> fail. So not packable. Suffix start=1: [2,9] -> used=1,rem=10; 2 fits rem=8; 9 fits? 9 <=8? Actually 9 >8, so used=2, rem=10-9=1; used=2 success. So answer=2. Our check(1) should succeed. Good.
Another: m=2, k=10, a=[1,9,2]. Full: 1->rem=9; 9 fits rem=0; 2>0 -> used=2, rem=10-2=8; success used=2. So packable, answer=3.
Now, consider case where many small items fill a box exactly, then a larger item opens new box. Our simulation handles.
Now, check monotonic: If suffix from i works, then from i+1 also works? Not necessarily; it's not monotonic in the other direction. But we only need monotonic as i increases (suffix shorter). That holds.
Edge: Suppose k=5, items [3,3,3]. m=2. Check(0): used=1,rem=5; 3 fits rem=2; 3>2 -> used=2, rem=5-3=2; 3>2 -> need third box -> fail. Check(1): [3,3] -> used=1,rem=5;3 fits rem=2;3>2 -> used=2, rem=5-3=2; used=2 success. Check(2): [3] success. So monotonic: false, true, true. So binary search finds smallest true index 1, ans=2.
All good.
Now, we might also consider using a while loop to directly find the minimal start without binary search: we could start from leftmost and simulate, and whenever we run out of boxes, we need to drop the leftmost object. But we would need to know how many to drop. However, we can maintain a left pointer L and right pointer R scanning? Not straightforward.
Binary search is simpler.
Time complexity: O(n log n) with small constant.
Now, final code.
But wait: The problem says Maksim will throw out the leftmost object from the set until the remaining set can be packed. That is exactly the process of increasing L. So the answer is n - L_min, where L_min is the smallest number of objects to discard such that the rest can be packed. So we are directly computing that.
Thus final.
I'll write the solution in C++.
Implementation:
#include
#include
using namespace std;
int n, m, k;
vector a;
bool check(int start) {
int used = 1;
int cur = k;
for (int i = start; i < n; ++i) {
if (a[i] <= cur) {
cur -= a[i];
} else {
++used;
if (used > m) return false;
cur = k - a[i];
}
}
return true;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m >> k;
a.resize(n);
for (int i = 0; i < n; ++i) cin >> a[i];
int lo = 0, hi = n-1;
// ensure hi is true (we know hi is true because a[n-1] <= k)
while (lo < hi) {
int mid = (lo + hi) / 2;
if (check(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
int ans = n - lo;
cout << ans << endl;
return 0;
}
But wait: check(n-1) is true, so hi = n-1 is true. That's correct.
Now, test: if n=1, hi=0, lo=0, loop not executed, ans = 1-0=1. check(0) would be true: used=1,cur=k; a[0]<=k, so cur reduces; success. Good.
Now, what if m=0? Not allowed.
Now, but there's a nuance: The algorithm starts with "he takes one of the empty boxes he has". That implies he must have at least one box to start. If m=0, he can't even take a box. But m>=1.
Now, is there any case where the suffix is empty (start = n)? Not used.
Now, we should consider if the answer could be 0? Possibly if all a_i > k? But a_i <= k, so at least last object fits. So answer >=1.
Thus done.
But wait, example 2 answer is 1, which matches.
Thus final.
Now, is there any potential off-by-one? Let's test scenario: n=2, m=1, k=3, a=[2,2]. check(0): used=1,cur=3; 2->cur=1; next 2>1 -> used would become 2 >1 -> false. So false. check(1): [2] -> true. lo=0, hi=1. mid=0: check(0) false -> lo=1. ans = 2-1=1. correct.
Scenario: n=2, m=2, k=3, a=[2,2]. check(0): 2->cur=1; 2>1 -> used=2, cur=3-2=1; success true. So lo=0, hi=1? Actually hi = n-1 =1, lo=0, mid=0, check(0) true -> hi=0. loop ends lo=0, ans=2. correct.
Thus code works.
Now, we need to consider if the algorithm might be misinterpreted: Could it be that when he takes a new empty box, he does not put the current object immediately, but rather goes back to the beginning of the objects? That would be weird and not match examples. So it's fine.
Thus final solution.
Given the problem's difficulty (likely Div2 C or B), binary search with linear check is appropriate.
Now, we might consider optimizing further: Since check is O(n) and we call it log n times, we can also early break if used > m. That's already done.
Now, final answer code.
But wait: There is a nuance: The algorithm says "if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box, and the remaining size of the box decreases by a_i. Otherwise he takes the new empty box and continues the process above." Could it be interpreted that after taking the new empty box, he continues from the beginning of the objects (i.e., rechecks all objects again)? That would be First-Fit? No, First-Fit would check from first box, not from start of objects. That would be a different algorithm (like restarting scan of boxes). But the phrase "continues the process above" likely refers to the process of going through objects, but he already is at the i-th object; continuing might mean he continues with the same i-th object but now with the new box. That's our interpretation.
Thus correct.
Now, we should also note that the problem title might be "Packaging" or something. But anyway.
Given all this, we'll produce final answer.
But wait: Could there be a scenario where the binary search with Next-Fit checker fails because the property "if suffix works then any shorter suffix works" does not hold for Next-Fit? Let's test: Suppose we have a suffix that works; we remove its first object, getting a shorter suffix. Could it become not packable? That would be weird because we have fewer items. The number of boxes needed cannot increase. It could stay the same or decrease. So it should still be ≤ m. So property holds.
Proof: Let S be a sequence. Let NF(S) be number of boxes used by Next-Fit. If we remove the first item, getting S', then NF(S') ≤ NF(S). Because we are processing a subsequence of S (specifically, the tail). However, is it always true that NF(S') ≤ NF(S)? Consider S = [large, small, large] maybe? For Next-Fit, the number of boxes is determined by the sequence. If we drop the first item, the remaining items might be packed differently. Could it require more boxes? Possibly if the first item helped to fill a box that otherwise would have been underfilled, causing later items to use more boxes? But Next-Fit doesn't look back; it only uses the current box. The presence of the first item influences the state (remaining capacity of the first box) when the second item is processed. Removing the first item means we start with a fresh box for the new first item (since we start with a new current box). That could actually reduce the number of boxes? Or increase? Let's test with an example:
Suppose k=10, items: [6,5,5]. NF: start box1:6->rem=4; 5>4->open box2:5->rem=5; 5 fits->rem=0; total boxes=2. If we drop first item, sequence [5,5]: box1:5->rem=5; 5 fits->rem=0; total boxes=1. So NF decreased.
Could NF increase? Consider [1,9,1,9] with k=10. NF: box1:1->rem=9; 9 fits->rem=0; 1>0->box2:1->rem=9; 9 fits->rem=0; boxes=2. Drop first item: [9,1,9]: box1:9->rem=1; 1 fits->rem=0; 9>0->box2:9->rem=1; boxes=2. Same.
Try to find case where dropping first item increases boxes. Suppose k=10, items: [5,6,5]. NF: box1:5->rem=5; 6>5->box2:6->rem=4; 5>4->box3:5->rem=5; boxes=3. Drop first: [6,5]: box1:6->rem=4; 5>4->box2:5->rem=5; boxes=2. Decrease.
What about [8,2,8]? k=10. NF: box1:8->rem=2; 2 fits->rem=0; 8>0->box2:8->rem=2; boxes=2. Drop first: [2,8]: box1:2->rem=8; 8 fits->rem=0; boxes=1. Decrease.
It seems dropping first cannot increase number of boxes. Intuitively, because you are starting with a fresh box, which might have more capacity than the previous first box after packing the first item. However, could it be that the first item used some capacity that allowed later items to be packed into the same box, and without it, later items might not fit together? Since Next-Fit never goes back, the first box after dropping might be the same as the second box originally? Actually, we need to compare.
Let original sequence S = x, S'. After packing S, we have some number of boxes. In packing S', we start with a fresh box. The packing of S' is independent. Could it use more boxes than S? Suppose S used 2 boxes, S' might use 3? But S' is a subsequence of S (specifically the tail). In any bin packing algorithm that is online and does not look ahead, processing a subsequence cannot require more bins than processing the full sequence? Not necessarily: For Next-Fit, consider that the presence of earlier items might cause the algorithm to close a box earlier, freeing a new box for later items, which could be beneficial? Actually, earlier items consume capacity, potentially causing later items to open new boxes earlier. Removing those earlier items might allow later items to be packed into the first box, reducing boxes. So it's unlikely to increase.
But could it increase? Suppose k=10, items: [9,1,9]. NF: box1:9->rem=1; 1 fits->rem=0; 9>0->box2:9->rem=1; boxes=2. Drop first: [1,9]: box1:1->rem=9; 9 fits->rem=0; boxes=1. Decrease.
What about [2,9,2,9]? NF: box1:2->rem=8; 9>8? Actually 9>8 -> box2:9->rem=1; 2>1->box3:2->rem=8; 9>8->box4:9->rem=1; boxes=4. Drop first: [9,2,9]: box1:9->rem=1; 2>1->box2:2->rem=8; 9>8? Actually 9>8 -> box3:9->rem=1; boxes=3. Decrease.
It seems monotonic non-increasing. I think it's true: For Next-Fit, the number of bins used for a sequence is a function that is monotone with respect to adding items at the front? Adding an item at the front can only increase or keep the same number of bins. This is intuitive: if you have a sequence and you prepend an item, you might need to open a new box at the start, and that could cause a cascade? But could it reduce? No, adding items can't reduce bins. So NF is monotonic non-decreasing when adding items at the front. Therefore, removing items from the front (i.e., taking a suffix) is monotonic non-increasing. So property holds.
Thus binary search is valid.
Now, final code.
We should also consider the possibility that m might be very large (2e5) and the used counter may never exceed m, but we still need to loop through all items. That's fine.
Now, double-check memory: a vector of size n (2e5) ints, fine.
Now, we should test with maximum n=m=200k, all a_i=1, k=1e9. Then check(start) will always succeed because all items fit in one box. Binary search will check mid points; each check will iterate from mid to n, so O(n log n) ~ 3.6M iterations, trivial.
If a_i are large such that each item opens a new box, used will increase. Still same iteration count.
Thus solution efficient.
Now, just to be thorough, let's test with some random small cases manually or via reasoning.
Case: n=3, m=2, k=5, a=[5,1,5]. Full: 5 fits rem=0; 1>0 -> used=2, rem=5-1=4; 5>4? used would become 3>2, fail. Check start=0 false. start=1: [1,5] -> used=1,rem=5; 1 fits rem=4; 5>4? used=2, rem=5-5=0; used=2 success. start=2: [5] success. So ans=2. Binary search: lo=0,hi=2. mid=1, check true -> hi=1; lo=0,hi=1,mid=0 check false -> lo=1; ans=2. Correct.
Case: n=4, m=2, k=6, a=[1,5,1,5]. Full: 1->rem=5;5 fits rem=0;1>0->used=2,rem=6-1=5;5 fits rem=0; used=2 success. So ans=4. Check start=0 true -> lo=0, ans=4.
Case: n=4, m=2, k=6, a=[1,5,2,5]. Full: 1->rem=5;5 fits rem=0;2>0->used=2,rem=6-2=4;5>4? need third box -> fail. start=1: [5,2,5] -> 5 fits rem=1? Actually start: used=1,rem=6;5 fits rem=1;2>1 -> used=2,rem=6-2=4;5>4 -> need third -> fail. start=2: [2,5] -> used=1,rem=6;2->rem=4;5>4? used=2,rem=6-5=1; success. So ans=2. Binary search: lo=0,hi=3; mid=1 check false -> lo=2; lo=2,hi=3,mid=2 check true -> hi=2; ans=2. Correct.
All good.
Thus final code is ready.
Now, let's think about potential pitfalls: The problem statement might have an alternative interpretation: Could "current box" refer to the box he is currently considering, and he checks each box in order? Actually, the phrase "he takes one of the empty boxes he has, goes from left to right through the objects, and if the i-th object fits in the current box (the remaining size of the box is greater than or equal to a_i), he puts it in the box" suggests that he has selected a box (the current box) and then processes objects; if an object doesn't fit, he takes a new empty box. This is Next-Fit.
But what about the phrase "takes the new empty box"? It might be interpreted as "takes a new empty box (i.e., from the pool) and then continues from the beginning of the objects"? That would be weird because he'd be in an infinite loop. So it's not that.
Thus solution stands.
Now, final answer: Provide C++ code.
We'll also mention the approach in explanation: binary search on starting index, simulate Next-Fit packing.
Now, we should also think about possible overflow in cur = k - a[i] if a[i] > k, but a_i ≤ k, so safe.
Now, write final answer with appropriate comments.
We'll also consider using long long for cur to be safe, but int is fine. I'll use long long to avoid any risk.
So final code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
// function to check if suffix starting at idx can be packed
auto can = [&](int idx) -> bool {
int used = 1; // we start with one box
long long rem = k; // remaining capacity of current box
for (int i = idx; i < n; ++i) {
if (a[i] <= rem) {
rem -= a[i];
} else {
++used;
if (used > m) return false;
rem = k - a[i];
}
}
return true;
};
int lo = 0, hi = n - 1; // hi is always packable (single last object)
while (lo < hi) {
int mid = (lo + hi) / 2;
if (can(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
int ans = n - lo;
cout << ans << "\n";
return 0;
}
We should double-check: In the binary search, we assume that hi (n-1) is always packable. Is it always true? a[n-1] ≤ k, so with one box it fits, so yes. So hi is packable. Good.
Edge case: n=1, hi=0, loop not executed, ans = 1-0=1. can(0) would be true but we don't call, but ans is correct.
Thus final.
But there is one nuance: The algorithm may start with "he takes one of the empty boxes he has" meaning he must have at least one box. Since m>=1, okay.
Now, we should also consider: Could there be a case where m is very small and the last object alone fails? For last object alone to fail, we would need a[n-1] > k, but a_i ≤ k, so it's fine.
Thus final answer.
Now, we can produce the solution.
Given the problem, I'll provide an explanation and the code.
But wait, the problem statement says: "Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change)." So he resets boxes each attempt. That's consistent with our simulation.
Thus final.
Now, I'll produce the final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
vector<int> a(n);
for (int i = 0; i < n; ++i) cin >> a[i];
// checks whether the suffix starting at index 'start' can be packed
auto can = [&](int start) -> bool {
int used = 1; // we always start with one box
long long rem = k; // remaining capacity of the current box
for (int i = start; i < n; ++i) {
if (a[i] <= rem) {
rem -= a[i];
} else {
++used;
if (used > m) return false;
rem = k - a[i];
}
}
return true;
};
// binary search for the smallest start index with a packable suffix
int lo = 0, hi = n - 1; // hi is always packable (single last object)
while (lo < hi) {
int mid = (lo + hi) / 2;
if (can(mid)) hi = mid;
else lo = mid + 1;
}
cout << n - lo << "\n";
return 0;
}