D - 画像回転エディタ / Image Rotation Editor 解説 by admin
DeepSeek V3Overview
This is a problem where you perform \(Q\) operations of rotating a \(K \times K\) subregion clockwise by 90 degrees on an \(N \times N\) grid, then output the resulting image.
Analysis
This problem can be solved by simply performing the rotation operation on the specified subregion for each operation. Since the constraints state “\(Q \times K^2 \leq 2 \times 10^7\)”, a straightforward approach of rotating the \(K \times K\) region for each operation is sufficiently fast. In other words, by repeatedly extracting the sub-grid, rotating it, and placing it back for each operation, we can obtain the final image state.
Algorithm
- Read the initial grid and convert to a 0-indexed coordinate system
- For each operation, perform the following:
- Extract the \(K \times K\) sub-grid starting from the specified top-left coordinate \((R_j, C_j)\)
- Rotate the extracted sub-grid clockwise by 90 degrees
- Write the rotated grid back to the original position
- Output the grid after all operations are completed
The sub-grid rotation is implemented using the property that element \((i, j)\) in the original sub-grid moves to position \((j, K-1-i)\) after rotation.
Complexity
- Time complexity: \(O(Q \times K^2)\)
- Because each operation accesses \(K^2\) elements
- Since \(Q \times K^2 \leq 2 \times 10^7\) from the constraints, this is sufficiently fast
- Space complexity: \(O(N^2)\)
- Memory for storing the grid
Implementation Notes
Coordinates are handled in 0-indexed form (since input is 1-indexed, subtracting 1 is necessary)
For rotating the sub-grid, create a new 2D array and then copy it back to the original position
The rotation operation can be written concisely using list comprehensions
Since the grid is updated directly after each operation, memory efficiency is good
Source Code
def main():
import sys
data = sys.stdin.read().splitlines()
first_line = data[0].split()
N = int(first_line[0])
K = int(first_line[1])
Q = int(first_line[2])
grid = []
for i in range(1, 1 + N):
grid.append(list(data[i].strip()))
operations = []
for i in range(1 + N, 1 + N + Q):
parts = data[i].split()
R = int(parts[0]) - 1
C = int(parts[1]) - 1
operations.append((R, C))
for (r, c) in operations:
subgrid = [[grid[r+i][c+j] for j in range(K)] for i in range(K)]
rotated = [[subgrid[K-1-j][i] for j in range(K)] for i in range(K)]
for i in range(K):
for j in range(K):
grid[r+i][c+j] = rotated[i][j]
for i in range(N):
print(''.join(grid[i]))
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.