日期:2025年8月13日
ZeroJudge 題目連結:c356. Justin 愛加密
解題想法
這題記憶體只有 16 MB,據說 Python 至少要用 32MB,如果記憶體太少一定會遇到 RE: code 127。要用 cstdio 函式庫中的 fgets,每次讀取指定長度的字元,這樣才能過關。
Python 程式碼
超過記憶體上限。
n = int(input())
s = input()
m = len(s)
d = -1
w = m//n
for i in range(0, m, n):
d = (d+1)%w
print(s[i+d], end="")
print()
C++ 程式碼
有些測資的字串太長,這樣寫過不了。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n; cin >> n;
string s; cin >> s;
int m = (int)s.size();
int d = -1, w = m/n;
for(int i=0; i<m; i+=n) {
d = (d+1)%w;
cout << s[i+d];
}
cout << "\n";
return 0;
}
改用 cstdio 函式庫中的 fgets,每次讀取指定長度的字元,語法為
fgets(字元陣列, 包含結尾的 \n 的字元陣列長度, 輸入來源)
使用時間約為 19 ms,記憶體約為 84 kB,通過測試。
#include <cstdio>
using namespace std;
int main() {
int n; scanf("%d\n", &n);
char s[n+1]; // 包含結尾的 \n,長度要開成 n+1
int d = 0; // 由字元陣列輸出字元用的索引值
for(int i=0; i<n; i++) { // 共執行 n 次
fgets(s, n+1, stdin); // 由 stdin 讀取長度為 n+1 的資料存入 s
printf("%c", s[d]); // 印出 s[d]
d = (d+1)%(n+1); // 更新 d,每隔 n+1 要輪回開頭
}
puts(""); // 印出換行
return 0;
}
沒有留言:
張貼留言