D - 荷物の運搬 / Transporting Cargo Editorial by admin Editorial for printing
Claude Opus 5 (High)Overview
In this problem, we are given \(N\) packages arranged in a line and want to divide them into at most \(K\) contiguous segments while preserving their order, so as to minimize the maximum sum of package weights among all segments. This is a classic “minimize the maximum” problem, which can be solved with binary search on the answer (binary search + greedy verification).
Analysis
Issues with the Naive Approach
The first idea that comes to mind is to try all possible ways to partition the packages. However, since we can choose whether or not to cut at each of the \(N-1\) split points, there are up to \(2^{N-1}\) ways to partition them, which will not run in time at all for \(N \le 10^5\).
Next, considering dynamic programming, we could define \(dp[i][j]\) as “the minimum cost when dividing the first \(i\) items into exactly \(j\) segments.” However, this requires \(O(NK)\) states, and transitions take around \(O(N^2K)\) time, which is completely infeasible for \(N, K \le 10^5\) (even with optimization, an \(O(NK)\) approach would require \(10^{10}\) operations, which is impossible).
Key Insight: Turning the Problem into a “Decision Problem” Instead of Searching for the Answer Directly
Here, we shift our perspective. Instead of directly answering “what is the minimum value?”, we consider the following Yes/No problem:
Decision Problem: “Can all packages be transported using at most \(K\) trucks such that the total weight on each truck is at most \(X\)?”
This decision problem exhibits monotonicity. That is:
- If it is possible for some \(X\) (Yes), it is definitely possible for any value larger than \(X\) (Yes).
- If it is not possible for some \(X\) (No), it is definitely not possible for any value smaller than \(X\) (No).
This holds because relaxing the upper bound only loosens the constraints, which cannot reduce our options.
Therefore, plotting the answers along the \(X\)-axis produces a pattern like No No No ... No Yes Yes Yes ..., and the minimum \(X\) that yields Yes is the answer we are looking for. This can be found using binary search.
The Decision Problem Can Be Solved with a Greedy Approach
To determine “whether the packages can be divided into at most \(K\) segments each with a sum at most \(X\),” we can find the minimum number of segments by simply packing items greedily from the beginning:
- If adding the next package to the current truck does not exceed \(X\), load it onto the current truck.
- If it exceeds \(X\), start a new truck and load the package onto it.
The reason this greedy strategy is optimal (minimizes the number of segments) is that there is nothing to gain by “putting a package on the next truck when it could still fit on the current one.” Cutting early only reduces the flexibility for subsequent partitions and never decreases the total number of segments.
Concrete Example: Consider \(A = (2, 5, 4, 1, 3)\) and \(K = 3\).
- When \(X = 6\): \([2]\) (adding 5 yields \(7 > 6\)) \(\to\) \([5]\) (adding 4 yields \(9 > 6\)) \(\to\) \([4, 1]\) (adding 3 yields \(8 > 6\)) \(\to\) \([3]\), taking a total of 4 trucks. Since \(4 > 3\), the result is No.
- When \(X = 7\): \([2, 5]\) \(\to\) \([4, 1]\) (adding 3 yields \(8 > 7\)) \(\to\) \([3]\), taking a total of 3 trucks. Since \(3 \le 3\), the result is Yes.
Thus, the answer is 7.
Algorithm
- Determine the search range for the binary search.
- Lower bound
lo\(= \max A_i\): In any partition, the truck containing the heaviest package must hold at least this weight. - Upper bound
hi\(= \sum A_i\): Loading everything onto a single truck is always feasible (\(K \ge 1\)).
- Lower bound
- While
lo < hi, letmid = (lo + hi) // 2and call the decision function.- Decision function: Greedily pack packages from left to right, count the required number of trucks
cnt, and return Yes ifcnt <= K. - If Yes, the answer is at most
mid, so updatehi = mid. - If No, the answer is strictly greater than
mid, so updatelo = mid + 1.
- Decision function: Greedily pack packages from left to right, count the required number of trucks
- When the loop terminates,
lo(\(=\)hi) is the answer.
Because lo starts from \(\max A_i\), the situation where a single package \(A_i\) exceeds mid will never happen inside the decision function, allowing us to safely run the greedy check without special edge-case handling.
Complexity
- Time Complexity: \(O(N \log(\sum A_i))\) — Each check takes \(O(N)\), and binary search performs \(O(\log(\sum A_i))\) iterations. Since \(\sum A_i \le 10^{14}\), the number of iterations is around 47. The total number of operations is roughly \(5 \times 10^6\), which is well within the time limit.
- Space Complexity: \(O(N)\) — Required only to store the array \(A\).
Implementation Notes
Setting the lower bound of binary search to \(\max A_i\) is important. If you start with
lo = 0orlo = 1, an individual package may exceedmidand fail to fit, which could cause an infinite loop in a naive greedy implementation or lead to incorrect results if branching is not handled properly. (With standard implementations,cntwould continue to increase and lead to a No result anyway, but setting the lower bound to \(\max A_i\) is standard practice for safety).In the check function, you can
breakas soon ascnt > Kto avoid unnecessary iterations.In Python, reading \(10^5\) lines using
input()repeatedly can be slow; reading all input at once usingsys.stdin.buffer.read().split()is much faster.Python handles arbitrarily large integers, so integer overflow is not a concern. However, in languages like C++, \(\sum A_i\) can reach up to \(10^{14}\), so you must use 64-bit integers (
long long).When
K = N, the answer is \(\max A_i\), and whenK = 1, the answer is \(\sum A_i\), which match the boundaries of the initial binary search range. These boundary cases are handled naturally.Source Code
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0]); k = int(data[1])
a = [int(x) for x in data[2:2+n]]
lo = max(a)
hi = sum(a)
while lo < hi:
mid = (lo + hi) // 2
cnt = 1
cur = 0
ok = True
for v in a:
if cur + v > mid:
cnt += 1
cur = v
if cnt > k:
ok = False
break
else:
cur += v
if ok:
hi = mid
else:
lo = mid + 1
sys.stdout.write(str(lo) + "\n")
main()
This editorial was generated by claude5opus-high.
posted:
last update: