公式

B - 手記の縦読み / Vertical Reading of a Memoir 解説 by admin 印刷ページ

gpt-6-astra-medium

Overview

The problem asks us to extract the \(K\)-th character from the left of each row and concatenate them from top to bottom.

Analysis

The secret message is obtained simply by reading the specified column from top to bottom. Therefore, a naive approach of extracting \(1\) character from each string is sufficient, and no optimization is needed.

For example, consider the case where \(H=3\), \(W=4\), and \(K=2\), and the note is as follows:

abcd
efgh
ijkl

The \(2\)-nd character from the left of each row is b, f, and j, respectively, so the answer is bfj.

A point to be careful of is that while the column indices in the problem statement are \(1\)-indexed, Python’s string indices are \(0\)-indexed. The \(K\)-th character from the left is extracted using S[K - 1]. If you use S[K], it will access a different column or cause an out-of-bounds error.

Algorithm

  1. Read \(H, W, K\), and the \(H\) strings.
  2. From top to bottom, extract the character at index \(K-1\) from each string.
  3. Concatenate the \(H\) extracted characters in order and output the result.

In the provided code, the input is split by whitespace and newlines and stored in data. Since the first \(3\) elements are \(H, W, K\), as \(i\) ranges from \(0\) to \(H-1\), the string of each row can be referenced by data[3 + i].

ans = ''.join(data[3 + i][K - 1] for i in range(H))

This operation extracts the target character from each row and joins them into a single string using join.

Complexity

  • Time complexity: \(O(HW)\)
  • Space complexity: \(O(HW)\)

Reading and storing the entire input takes \(O(HW)\) time and space, respectively. If we only consider the process of extracting the characters and constructing the answer after reading the input, both the time and auxiliary space complexities are \(O(H)\).

Key Implementation Points

  • Access the \(K\)-th character from the left using the index K - 1.

  • Processing the rows without changing their order yields the message read from top to bottom.

  • Although W is read from the input, it is not used in the subsequent process because we only need to extract the character at the specified position from each row.

  • Output the answer on a single line as a string of length \(H\) without any spaces in between.

    Source Code

import sys

def main():
    data = sys.stdin.read().split()
    H, W, K = int(data[0]), int(data[1]), int(data[2])
    ans = ''.join(data[3 + i][K - 1] for i in range(H))
    sys.stdout.write(ans + '\n')

main()

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

投稿日時:
最終更新: