Official

D - 荷物の運搬 / Transporting Cargo Editorial by admin Editorial for printing

Gemini 3.8 Flash (High)

Overview

This problem asks us to divide \(N\) ordered packages into at most \(K\) trucks without changing their order, and to minimize the maximum total weight loaded onto any single truck.

Analysis

Naive Approach and Its Limitations

Dividing the packages among at most \(K\) trucks is equivalent to choosing where to place partitions between the packages. However, there are up to \(\binom{N-1}{K-1}\) ways to place the partitions. With constraints as large as \(N, K \leq 10^5\), searching through all possibilities is impossible. Furthermore, even if we use dynamic programming (DP), the number of states would be too large, leading to a Time Limit Exceeded (TLE).

Rephrasing as a Decision Problem (Binary Search)

This problem falls under the common competitive programming theme of “minimizing the maximum value.” For such problems, the standard strategy is not to “find the answer directly,” but rather to rephrase it into a Yes/No decision problem: “Can all packages be transported using at most \(K\) trucks when the maximum load capacity is set to a given value \(P\)?”

This decision problem exhibits the following monotonicity: - The larger the capacity limit \(P\) per truck, the more packages each truck can carry, which decreases the number of required trucks. - Conversely, if \(P\) is too small, the number of required trucks increases and will exceed \(K\).

Because there is a boundary where “the condition is satisfied for values greater than or equal to a threshold, and not satisfied for values less than it,” we can use binary search to efficiently identify the minimum \(P\) that serves as the answer.

Solving the Decision Problem (Greedy Approach)

When fixing the upper limit to \(P\), the optimal way to minimize the number of trucks is using a greedy approach: “pack packages into each truck as much as possible as long as the total weight does not exceed \(P\).” We iterate through the packages from front to back. Whenever adding the next package to the current truck would cause the total weight to exceed \(P\), we move on to use a new truck. Since this can be checked with a single pass through the packages, the decision problem can be solved quickly in \(O(N)\) time.

Algorithm

  1. Determine the search range:
    • Lower bound left: \(\max(A)\) (since each truck must be able to carry at least the single heaviest package)
    • Upper bound right: \(\sum A\) (the case where all packages are carried by a single truck)
  2. Binary search:
    • While left < right, calculate the midpoint mid = (left + right) // 2 and simulate the process with mid as the maximum load capacity.
    • Greedily load packages from the front and determine whether the number of trucks needed is at most \(K\).
      • Possible (possible = True): Since it may be possible to reduce the capacity further, set right = mid.
      • Impossible (possible = False): Since the capacity is insufficient, set left = mid + 1.
  3. When the binary search terminates, left will be the desired minimum value.

Complexity

  • Time Complexity: \(O(N \log(\sum A))\)
    • The search range width is at most \(\sum A \leq 10^5 \times 10^9 = 10^{14}\).
    • The number of binary search steps is approximately \(\log_2(10^{14}) \approx 47\).
    • Since each step scans the array once (\(O(N)\)), the total number of operations is around \(47 \times 10^5 \approx 4.7 \times 10^6\), which easily runs well within the time limit.
  • Space Complexity: \(O(N)\)
    • Requires \(O(N)\) memory to store the list of package weights \(A\).

Implementation Notes

  • Initial values for binary search:

    • Initializing left to max(A) prevents individual package weights from exceeding mid during the simulation, which avoids infinite loops or unexpected edge-case behaviors.
  • Fast I/O:

    • Because \(N\) can be as large as \(10^5\), reading the entire input at once using sys.stdin.read().split() in Python significantly reduces execution time.
  • Integer overflow:

    • The total weight can reach up to \(10^{14}\), which exceeds the range of a 32-bit integer (approx. \(2 \times 10^9\)). While Python automatically handles arbitrarily large integers, languages such as C++ require a 64-bit integer type (long long).

      Source Code

import sys


def solve():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    N = int(input_data[0])
    K = int(input_data[1])
    A = [int(x) for x in input_data[2 : N + 2]]

    left = max(A)
    right = sum(A)

    while left < right:
        mid = (left + right) // 2

        count = 1
        current_weight = 0
        possible = True
        for a in A:
            if current_weight + a <= mid:
                current_weight += a
            else:
                count += 1
                current_weight = a
                if count > K:
                    possible = False
                    break

        if possible:
            right = mid
        else:
            left = mid + 1

    print(left)


if __name__ == "__main__":
    solve()

This editorial was generated by gemini-3.8-flash-high.

posted:
last update: