日期:2026年11月23日
ZeroJudge 題目連結:n130.p2. 製作看板
解題想法
先讀取看板尺寸 $m \times n$,再讀取要放入看板的字串 $s$,最後讀取 $m$ 列的看板樣式存入陣列 $board$。這題的測資 2 是極端狀況,要輸出到看板上的內容是空的,如果用 C++ 解題時,這個空行會被 cin 跳過,直接讀到看板的格式。如果用 Python 解題並用 input() 讀取測資,會讀到空行,反而沒有這個問題。為了處理測資 2,需要在讀取 $s$ 之後,檢查 $s$ 的開頭是否為看板樣式的 # 或 .,如果是,代表要輸出到看板上的內容是空的,直接讀到看板樣式。
Python 程式碼
使用時間約為 13 ms,記憶體約為 9.9 MB,通過測試。
def solve():
import sys
result = []
data = sys.stdin.read().split()
ptr = 0
while ptr < len(data):
m = int(data[ptr]) # 看板尺寸 m*n
n = int(data[ptr + 1])
ptr += 2
s = data[ptr] # 要放入看板的字串
ptr += 1
board = [] # 看板
# 要印出的內容 s 可能是空的,會被 .split() 跳過,直接讀到看板格式
if s[0] in "#.": # 讀到看板格式
board.append(list(s))
s = "" # s 重設為空字串
for _ in range(m - 1):
board.append(list(data[ptr]))
ptr += 1
else: # s 是要填入的內容
for _ in range(m):
board.append(list(data[ptr]))
ptr += 1
# 找出空格位置
space = []
for i in range(m):
for j in range(n):
if board[i][j] == '.':
space.append((i, j))
# 填入字串
d, p = len(s), len(space) # 字串長度,空格數量
start = 0 if d >= p else (p - d) // 2 # 開頭空格數量
a, b = start, 0 # 填入格子的索引值,讀取 s 的索引值
while a < p and b < d:
r, c = space[a]
board[r][c] = s[b]
a += 1
b += 1
# 輸出看板內容
for row in board:
res = "".join(row)
result.append(f"{res}\n")
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
使用時間約為 13 ms,記憶體約為 9.8 MB,通過測試。
while True:
try:
m, n = map(int, input().split()) # 看板尺寸 m*n
except EOFError:
break
s = input() # 要放入看板的字串
board = [list(input()) for _ in range(m)] # 看板格式
# 找出空格位置
space = []
for i in range(m):
for j in range(n):
if board[i][j] == '.':
space.append((i, j))
# 填入字串
d, p = len(s), len(space) # 字串長度,空格數量
start = 0 if d >= p else (p - d) // 2 # 開頭空格數量
a, b = start, 0 # 填入格子的索引值,讀取 s 的索引值
while a < p and b < d:
r, c = space[a]
board[r][c] = s[b]
a += 1
b += 1
# 輸出看板內容
for row in board:
print("".join(row))
C++ 程式碼
使用時間約為 1 ms,記憶體約為 3.8 MB,通過測試。
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int m, n; // 看板尺寸 m*n
string s; // 字串
vector<string> board; // 看板
while(cin >> m >> n) {
// 讀取要放入的字串 s、看板格式
board.assign(m, "");
string tmp; // 暫存用的字串
cin >> tmp; // 要印出的內容 s 可能是空的,會被 cin 跳過,直接讀到看板格式
if (tmp[0] == '#' || tmp[0] == '.') { // 讀到看板格式
board[0] = tmp;
for(int i = 1; i < m; i++) {
cin >> board[i];
}
} else { // 要填入的內容
s = tmp;
for(int i = 0; i < m; i++) {
cin >> board[i];
}
}
// 找出空格位置
vector<pair<int, int>> space;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if (board[i][j] == '.') {
space.push_back({i, j});
}
}
}
// 填入字串
int d = (int)s.size(), p = (int)space.size(); // 字串長度,空格數量
int start = (d >= p ? 0 : (p - d) / 2); // 開頭空格數量
for(int i = start, j = 0; i < p && j < d; i++, j++) {
int r = space[i].first, c = space[i].second;
board[r][c] = s[j];
}
// 輸出看板內容
for(auto row : board) {
cout << row << "\n";
}
}
return 0;
}
沒有留言:
張貼留言