公式

B - ロープの収納 / Storing the Rope 解説 by admin

Claude 4.6 Opus (Thinking)

Overview

This problem asks for the minimum number of times you need to fold a rope of length \(L\) in half (using ceiling division) to make its length \(W\) or less.

Analysis

Problem Breakdown

When the rope has length \(x\), folding it once results in a length of \(\lceil x/2 \rceil\). We want to repeat this until the length is \(W\) or less.

Example: \(L = 11\), \(W = 3\)

Folds Length
0 11
1 \(\lceil 11/2 \rceil = 6\)
2 \(\lceil 6/2 \rceil = 3\)

After 2 folds, the length becomes \(W = 3\) or less, so the answer is 2.

Is a Naive Approach Sufficient?

At first glance, \(L\) can be up to \(10^{18}\), which might seem concerning. However, since each operation roughly halves the length, the number of loop iterations is at most about \(\log_2(10^{18}) \approx 60\). This is fast enough, so we can solve the problem by simply simulating the process.

Implementing Ceiling Division

To compute \(\lceil x/2 \rceil\) using integer arithmetic, we use \((x + 1) \div 2\) (floor division).

  • \(x = 11\) (odd): \((11 + 1) / 2 = 6\) ✓ (\(\lceil 11/2 \rceil = 6\))
  • \(x = 6\) (even): \((6 + 1) / 2 = 3\) ✓ (\(\lceil 6/2 \rceil = 3\))

In general, the ceiling of dividing integer \(x\) by integer \(d\) is \(\lceil x/d \rceil = \lfloor (x + d - 1) / d \rfloor\). When \(d = 2\), this becomes \((x + 1) // 2\).

Algorithm

  1. Initialize a counter count to \(0\).
  2. While \(L > W\), repeat the following:
    • Update \(L\) to \(\lceil L/2 \rceil = (L + 1) // 2\).
    • Increment count by \(1\).
  3. Output count.
L, W = map(int, input().split())
count = 0
while L > W:
    L = (L + 1) // 2
    count += 1
print(count)

Complexity

  • Time complexity: \(O(\log L)\) (since the length roughly halves each time, the loop runs at most about \(60\) times)
  • Space complexity: \(O(1)\)

Implementation Notes

  • Ceiling division technique: (L + 1) // 2 correctly computes \(\lceil L/2 \rceil\). In Python, // performs floor division (for positive numbers), so the technique of adding \(d - 1 = 1\) to the numerator can be used.

  • When the condition is already satisfied: When \(L \leq W\), the while loop is never entered and count = 0 is output as-is, so no special case handling is needed.

  • Arbitrary-precision integers: \(L\) can be up to \(10^{18}\), but Python has no integer overflow, so it can be handled directly. If using C++ or similar languages, you need to use long long type.

    Source Code

L, W = map(int, input().split())
count = 0
while L > W:
    L = (L + 1) // 2
    count += 1
print(count)

This editorial was generated by claude4.6opus-thinking.

投稿日時:
最終更新: