# 0-6 進階輸入輸出 講義不是我寫的,網址在此 https://emanlaicepsa.github.io/2020/10/21/0-index/ 我只是將自己寫的練習題程式碼記錄下來。 最後更新日期:2024年10月5日 ## [TOJ: 5 / Hello World!](https://toj.tfcis.org/oj/pro/5/) ### Python 程式碼 執行時間最久約為 46 ms,使用記憶體最多約為 4120 kB,通過測試。 ```python= name = input() print(f"Hello ,{name:s} !") ``` ### C++ 程式碼 執行時間最久約為 2 ms,使用記憶體最多約為 312 kB,通過測試。 ```cpp= #include <iostream> #include <string> using namespace std; int main() { string name; getline(cin, name); cout << "Hello ," << name << " !\n"; return 0; } ``` ## [TOJ: 355 / [05校內初選]B.裝弱](https://toj.tfcis.org/oj/pro/355/) ### Python 程式碼 第2筆測資記憶體爆掉。 ```python= N, K = map(int, input().split()) data = sorted(list(map(int, input().split())), reverse=True) print(data[1]) ``` 改用自訂函式寫出類似 C++ stringstream 的工具,這次變成第二筆測資超時。 ```python= def stringStream(s, sep): start = 0 for end in range(len(s)): if s[end] in sep: yield s[start:end] start = end + 1 if start < len(s): yield s[start:] N, K = map(int, input().split()) stream = stringStream(input(), " \n") data = sorted([int(s) for s in stream], reverse=True) print(data[1]) ``` 再改成以下的寫法,還是超時。 ```python= def stringStream(s, sep): start = 0 for end in range(len(s)): if s[end] in sep: yield s[start:end] start = end + 1 if start < len(s): yield s[start:] N, K = map(int, input().split()) stream = stringStream(input(), " \n") high, ans = 0, 0 for s in stream: n = int(s) if n > high: ans = high high = n elif n > ans: ans = n print(ans) ``` ### C++ 程式碼 執行時間最久約為 559 ms,使用記憶體最多約為 388 kB,通過測試。 ```cpp= #include<iostream> using namespace std; int main() { ios::sync_with_stdio(0),cin.tie(0); int N, K; cin >> N >> K; int high = 0, ans = 0; for(int i=0, n; i<N; i++) { cin >> n; if (n > high) { ans = high; high = n; } else if (n > ans) { ans = n; } } cout << ans << "\n"; return 0; } ``` ------ ###### tags:`演算法`、`APCS`、`Python`、`C++`