Official

A - 縞模様の布 / Striped Cloth Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

Alternately concatenate \(K\) Rs and \(K\) Bs, and once the length reaches \(N\) or more, output the first \(N\) characters.

Analysis

We can simulate the coloring process described in the problem statement directly through string operations.

In Python, writing "R" * k creates a string consisting of \(K\) consecutive Rs. Using this, we can append \(K\) characters of the current color to the answer at a time.

What we need to be careful of is when the last stripe is shorter than \(K\) squares. If we directly output the string after appending \(K\) characters each time, the length might exceed \(N\), resulting in an incorrect answer.

Therefore, we construct the string until its length is at least \(N\), and finally extract only the first \(N\) characters.

For example, when \(N=8,\ K=3\), the string changes as follows:

  • RRR
  • RRRBBB
  • RRRBBBRRR

Finally, taking the first \(8\) characters gives the answer RRRBBBRR.

Since the constraints are small, this naive string construction will easily run in time.

Algorithm

  1. Initialize the string s representing the answer to an empty string.
  2. Set the initial color color to R.
  3. While the length of s is less than \(N\), repeat the following:
    • Append a string of \(K\) consecutive color characters to s.
    • Switch color to B if it is R, and to R if it is B.
  4. Output the first \(N\) characters of s.

Since we add red first and switch colors every time \(K\) characters are appended, the striped pattern described in the problem statement is formed. By simply truncating the excess suffix, we can handle cases where the last stripe is shorter than \(K\).

Complexity

Let \(M=\lceil N/K\rceil\) be the number of stripes added.

  • Time complexity: \(O(KM^2)\)
  • Space complexity: \(O(KM)=O(N+K)\)

The time complexity is evaluated considering the case where the existing string is copied during each concatenation. The lengths of the string at each step are \(K,2K,\ldots,MK\), so their sum is \(O(KM^2)\). Under the given constraints, this runs fast enough.

Implementation Notes

  • color * k creates a string of \(K\) consecutive characters of the current color.

  • By using while len(s) < n:, the loop terminates once the required length is reached.

  • s[:n] extracts the first \(N\) characters. With this, no special branching is required even when \(N\) is not a multiple of \(K\).

  • Even when \(K>N\), extracting the first \(N\) characters from the initially created red stripe produces the correct output.

    Source Code

# 問題文から独立に実装: R を K 個、B を K 個と交互に足していき、N 文字で切る
n, k = map(int, input().split())
s = ""
color = "R"
while len(s) < n:
    s += color * k
    color = "B" if color == "R" else "R"
print(s[:n])

This editorial was generated by gpt-6-astra-medium.

posted:
last update: