日期:2026年9月28日
ZeroJudge 題目連結:c381.聖經密碼
解題想法
題目是多筆測資。每組測資第一行是兩個整數 $n, m$,如果 $n, m$ 皆為 $0$ 代表測資結束。接下來用 $n$ 行,每行一個字串,要將這些字串接成一個很長的字串 $s$。下一行有 $m$ 個整數,代表從 $s$ 之中取出字元的位置,這些位置由 $1$ 開始計算,轉成索引值要 $-1$。將取出的字元接成一個字串 $t$,最後印出 $t$。
這題我最早是在2024年10月2日寫過的,最近看到題目更新了,才在2026年9月28日回來重寫,但是原來可以 AC 的 Python 程式碼卻會吃 TLE,後來改用 sys 加速輸入、輸出才 AC,可能題目更新後測資量變很大吧!
Python 程式碼
2024年10月2日測試,解題時間約為 0.2 s,使用記憶體約為 12.9 MB。但是2026年9月28日題目更新後測試,TLE。
while True:
n, m = map(int, input().split()) # 字串數量 n,索引值數量 m
if n == 0 and m == 0: break # 中止程式的條件
s = "" # 字串內容
for _ in range(n): s += input() # 讀取 n 行字串
t = "" # 答案
indices = list(map(int, input().split())) # 索引值,1-indexed
for idx in indices: t += s[idx - 1] # 組合答案
print(t)
2026年9月28日題目更新後測試,解題時間約為 71 ms,使用記憶體約為 26.4 MB。
def solve():
import sys
def get_tokens():
for line in sys.stdin:
for part in line.split():
yield part
data = get_tokens()
while True:
n = int(next(data)) # 字串數量 n
m = int(next(data)) # 索引值數量 m
if n == 0 and m == 0: break # 中止程式的條件
s = "".join(next(data) for _ in range(n)) # 字串內容
t = [s[int(next(data)) - 1] for _ in range(m)] # 組合答案
sys.stdout.write(f"{"".join(t)}\n")
if __name__ == "__main__":
solve()
C++ 程式碼
2026年9月28日題目更新後測試,解題時間約為 26 ms,使用記憶體約為 14.2 MB。
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, m; // 字串數量 n,索引值數量 m
while(cin >> n >> m && (n != 0 || m != 0)) {
string s, t, u; // 字串內容,答案,暫存用的字串
for(int i = 0; i < n; i++) { // 讀取 n 行字串
cin >> u;
s += u;
}
int idx; // 索引值,1-indexed
for(int i = 0; i < m; i++) { // 組合答案
cin >> idx;
t += s[idx - 1];
}
cout << t << "\n";
}
return 0;
}
沒有留言:
張貼留言