# C++ 基礎語法練習題:Unit-5 迴圈 (while)、進階迴圈控制 (continue/break) 講義不是我寫的,原文連結為 [Yui Huang 演算法學習筆記:C++ 基礎語法](https://yuihuang.com/syntax/) 我只是將自己寫的練習題程式碼記錄下來。 最後更新日期:2024年11月10日 ## [ZeroJudge: d070. 格瑞哥里的煩惱 (0 尾版)](https://zerojudge.tw/ShowProblem?problemid=d070) ### Python 程式碼 執行時間最久約為 20 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= while True: y = int(input()) if y == 0: break if y%400 == 0: print("a leap year") elif y%100 == 0: print("a normal year") elif y%4 == 0: print("a leap year") else: print("a normal year") ``` ### C++ 程式碼 執行時間最久約為 3 ms,使用記憶體最多約為 300 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { while(true) { int y; cin >> y; if (y == 0) break; if (y%400 == 0) cout << "a leap year\n"; else if (y%100 == 0) cout << "a normal year\n"; else if (y%4 == 0) cout << "a leap year\n"; else cout << "a normal year\n"; } return 0; } ``` ## [ZeroJudge: d072. d071. 格瑞哥里的煩惱 (EOF 版)](https://zerojudge.tw/ShowProblem?problemid=d071) ### Python 程式碼 寫法1,使用 try ... except,執行時間最久約為 20 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= while True: try: y = int(input()) if y%400 == 0: print("a leap year") elif y%100 == 0: print("a normal year") elif y%4 == 0: print("a leap year") else: print("a normal year") except: break ``` 寫法2,使用 sys.stdin,執行時間最久約為 18 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= import sys for line in sys.stdin: y = int(line) if y%400 == 0: print("a leap year") elif y%100 == 0: print("a normal year") elif y%4 == 0: print("a leap year") else: print("a normal year") ``` ### C++ 程式碼 執行時間最久約為 3 ms,使用記憶體最多約為 304 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int y; while(cin >> y) { if (y%400 == 0) cout << "a leap year\n"; else if (y%100 == 0) cout << "a normal year\n"; else if (y%4 == 0) cout << "a leap year\n"; else cout << "a normal year\n"; } return 0; } ``` ## [ZeroJudge: e834. P1.批發出貨(Wholesale)](https://zerojudge.tw/ShowProblem?problemid=e834) ### Python 程式碼 執行時間最久約為 40 ms,使用記憶體最多約為 3.5 MB,通過測試。 ```python= m = int(input()) ns = list(map(int, input().split()))[:-1] for n in ns: r = n%m if r == 0: print(n//m) else: print(m-r) ``` ### C++ 程式碼 執行時間最久約為 5 ms,使用記憶體最多約為 336 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int m, n, r; cin >> m; while(true) { cin >> n; if (n == 0) break; r = n%m; if (r == 0) cout << n/m << "\n"; else cout << m-r << "\n"; } return 0; } ``` ## [ZeroJudge: a148. You Cannot Pass?!](https://zerojudge.tw/ShowProblem?problemid=a148) ### Python 程式碼 執行時間最久約為 17 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= import sys for line in sys.stdin: line = tuple(map(int, line.split())) standard = line[0]*59 isum = sum(line[1:]) print("yes" if isum <= standard else "no") ``` ### C++ 程式碼 執行時間最久約為 2 ms,使用記憶體最多約為 300 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int n, standard, score, total; while(cin >> n) { standard = n*59; total = 0; for(int i=0; i<n; i++) { cin >> score; total += score; } cout << (total <= standard ? "yes" : "no") << "\n"; } return 0; } ``` ## [ZeroJudge: d010. 盈數、虧數和完全數](https://zerojudge.tw/ShowProblem?problemid=d010) **此題是多筆測資,題目沒有說清楚。** ### Python 程式碼 執行時間最久約為 41 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= import sys for line in sys.stdin: n = int(line) s = 1 for i in range(2, n//2 + 1): if n%i == 0: s += i if s > n: print("盈數") elif s < n: print("虧數") else: print("完全數") ``` ### C++ 程式碼 執行時間最久約為 8 ms,使用記憶體最多約為 308 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int n; while(cin >> n) { int s = 1; for(int i=2; i<=n/2; i++) if (n%i == 0) s += i; if (s > n) cout << "盈數\n"; else if (s < n) cout << "虧數\n"; else cout << "完全數\n"; } return 0; } ``` ## [ZeroJudge: c067. 00591 - Box of Bricks](https://zerojudge.tw/ShowProblem?problemid=c067) ### Python 程式碼 執行時間最久約為 19 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= idx = 0 while True: n = int(input()) if n == 0: break if idx > 0: print() idx += 1 bricks = tuple(map(int, input().split())) total = sum(bricks) avg = total // n ans = 0 for brick in bricks: if brick < avg: ans += avg - brick print(f"Set #{idx:d}") print(f"The minimum number of moves is {ans:d}.") ``` ### C++ 程式碼 執行時間最久約為 2 ms,使用記憶體最多約為 320 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int idx = 0; while(true) { int n; cin >> n; if (n == 0) break; if (idx > 0) cout << "\n"; // 除了第一次執行以外,要印出換行 idx++; int bricks[n], total = 0; for(int i=0; i<n; i++) { cin >> bricks[i]; total += bricks[i]; } int avg = total / n, ans = 0; for(int i=0; i<n; i++) if (bricks[i] < avg) ans += avg - bricks[i]; cout << "Set #" << idx << "\n"; cout << "The minimum number of moves is " << ans << ".\n"; } return 0; } ``` ## [ZeroJudge: a010. 質因數分解](https://zerojudge.tw/ShowProblem?problemid=a010) ### Python 程式碼 執行時間最久約為 0.2 s,使用記憶體最多約為 3.3 MB,通過測試。 ```python= n = int(input()) # 要測試的數字 for i in range(2, n+1): # 依序檢測 2 ~ n order = 0 # 質因數的次方 flag = False # i 是否為質因數 while n%i == 0: # 如果 n 可以被 i 整除繼續執行 flag = True # flag 設定為 True order += 1 # 次方加 1 n //= i # n 除等於 i if flag: # 如果 flag 為 True if order >= 2: # 如果次方大於等於 2 print(f"{i:d}^{order:d}", end="") # 輸出的部分包含次方 else: # 否則只要輸出質因數 print(f"{i:d}", end="") if n != 1: print(" * ", end="") # 如果 n 不等於 1,還有其它質因數,印出 * if n == 1: break # 如果 n 等於 1,不需要再分解,中止迴圈 print() # 換行 ``` ### C++ 程式碼 執行時間最久約為 3 ms,使用記憶體最多約為 336 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int n; cin >> n; // 要測試的數字 for(int i=2; i<=n; i++) { // 依序檢測 2 ~ n int order = 0; // 質因數的次方 bool flag = false; // i 是否為質因數 while(n%i == 0) { // 如果 n 可以被 i 整除繼續執行 flag = true; // flag 設定為 True order++; // 次方加 1 n /= i; // n 除等於 i } if (flag) { // 如果 flag 為 True if (order >= 2) // 如果次方大於等於 2 cout << i << "^" << order; // 輸出的部分包含次方 else // 否則只要輸出質因數 cout << i; if (n != 1) cout << " * "; // 如果 n 不等於 1,還有其它質因數,印出 * } if (n == 1) break; // 如果 n 等於 1,不需要再分解,中止迴圈 } cout << "\n"; // 換行 return 0; } ``` ## [ZeroJudge: a147. Print it all](https://zerojudge.tw/ShowProblem?problemid=a147) ### Python 程式碼 執行時間最久約為 43 ms,使用記憶體最多約為 4.3 MB,通過測試。 ```python= while True: n = int(input()) if n == 0: break for i in range(1, n): if i%7: print(i, end="\n" if i==n-1 else " ") ``` ### C++ 程式碼 執行時間最久約為 6 ms,使用記憶體最多約為 304 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { while(true) { int n; cin >> n; if (n == 0) break; for(int i=1; i<n; i++) if (i%7) cout << i << " \n"[i == n-1]; } return 0; } ``` ## [ZeroJudge: e969. 大吃大喝 (Big eater)](https://zerojudge.tw/ShowProblem?problemid=e969) 需要注意輸出的文字,一定要完全按照題目的要求: 1. 如果一開始就沒有足夠的錢,直接輸出 **Wayne can't eat and drink.**。 2. 若食物為 Apple pie,輸出為 **eats an Apple pie**;若食物為 Corn soup,輸出為 **drinks a Corn soup**。 3. 如果錢正好花完,輸出為 **doesn't have money.**;如果剩下的錢為 1 元,輸出為 **has 1 dollar.**;如果剩下的錢大於 1 元,輸出為 **has {n:d} dollars.**。 ### Python 程式碼 執行時間最久約為 20 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= n, m, k = map(int, input().split()) t = 0 food = ("eats an Apple pie", "drinks a Corn soup") imin = (32, 55) if n < imin[k]: print("Wayne can't eat and drink.") else: while n >= imin[k]: n -= imin[k] print(f"{t:d}: Wayne {food[k]:s}, and now he ", end="") if n == 0: print(f"doesn't have money.") elif n == 1: print(f"has 1 dollar.") else: print(f"has {n:d} dollars.") k = (k+1)%2 t += m ``` ### C++ 程式碼 執行時間最久約為 7 ms,使用記憶體最多約為 336 kB,通過測試。 ```cpp= #include <iostream> #include <string> using namespace std; int main() { int n, m, k; cin >> n >> m >> k; int t = 0; string food[2] = {"eats an Apple pie", "drinks a Corn soup"}; int imin[2] = {32, 55}; if (n < imin[k]) { cout << "Wayne can't eat and drink.\n"; } else { while(n >= imin[k]) { n -= imin[k]; cout << t << ": Wayne " << food[k] << ", and now he "; if (n == 0) cout << "doesn't have money.\n"; else if (n == 1) cout << "has 1 dollar.\n"; else cout << "has " << n << " dollars.\n"; k = (k+1)%2; t += m; } } return 0; } ``` ## [ZeroJudge: c079. 10346 - Peter's Smokes](https://zerojudge.tw/ShowProblem?problemid=c079) ### Python 程式碼 執行時間最久約為 20 ms,使用記憶體最多約為 3.5 MB,通過測試。 ```python= import sys for line in sys.stdin: n, k = map(int, line.split()) # 一開始的數量 n,每 k 根捲成 1 根 ans = 0 # 答案預設為 0 while n > k: # 如果 n 大於 k,還能捲成新的菸,繼續執行 ans += (n//k) * k # n//k 的整數部分為捲成的菸數量,再乘以 k,加到 ans n = n%k + n//k # 更新n,n%k 為剩下的菸數量,n//k 的整數部分為捲成的菸數量 ans += n # ans 加上剩下的 n print(ans) # 輸出 ans ``` ### C++ 程式碼 執行時間最久約為 5 ms,使用記憶體最多約為 288 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int n, k; // 一開始的數量 n,每 k 根捲成 1 根 while(cin >> n >> k) { // 如果有讀到 n、k 繼續執行 int ans = 0; // 答案預設為 0 while(n > k) { // 如果 n 大於 k,還能捲成新的菸,繼續執行 ans += (n/k) * k; // n/k 的整數部分為捲成的菸數量,再乘以 k,加到 ans n = n%k + n/k; // 更新n,n%k 為剩下的菸數量,n/k 的整數部分為捲成的菸數量 } ans += n; // ans 加上剩下的 n cout << ans << "\n"; // 輸出 ans } return 0; } ``` ## [ZeroJudge: d053. 10970 - Big Chocolate](https://zerojudge.tw/ShowProblem?problemid=d053) 巧克力尺寸 $m \times n$ 可能有以下4種狀況 1. $1 \times 1$:不需要切,輸出 0。 2. $1 \times n$:只要切一個方向,輸出 $n-1$。 3. $m \times 1$:只要切一個方向,輸出 $m-1$。 4. $m, n > 1$:先切 $m$ 的方向 $m-1$ 次,再切 $n$ 的方向 $m \times (n-1)$。 ### Python 程式碼 執行時間最久約為 24 ms,使用記憶體最多約為 3.8 MB,通過測試。 ```python= import sys for line in sys.stdin: m, n = map(int, line.split()) if m == 1 and n == 1: print(0) elif m == 1: print(n-1) elif n == 1: print(m-1) else: print((m-1) + m*(n-1)) ``` ### C++ 程式碼 執行時間最久約為 11 ms,使用記憶體最多約為 312 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int m, n; while(cin >> m >> n) { if (m == 1 && n == 1) cout << "0\n"; else if (m == 1) cout << n-1 << "\n"; else if (n == 1) cout << m-1 << "\n"; else cout << m-1 + m*(n-1) << "\n"; } return 0; } ``` ## [ZeroJudge: d189. 11150 - Cola](https://zerojudge.tw/ShowProblem?problemid=d189) ### Python 程式碼 執行時間最久約為 19 ms,使用記憶體最多約為 3.3 MB,通過測試。 ```python= import sys for line in sys.stdin: n = int(line) ans = n # 答案至少有 n 瓶 while n >= 3: # 如果 n 大於等於 3,還可以再換到新的可樂 ans += n//3 # ans 加上換來的可樂數量 n/3 n = n//3 + n%3 # 更新 n,n//3 是換來的數量,n%3 是剩下的數量 if n == 2: ans += 1 # 如果剩 2 瓶,可以借 1 個空瓶,ans 加 1 print(ans) # 印出答案 ``` ### C++ 程式碼 執行時間最久約為 2 ms,使用記憶體最多約為 304 kB,通過測試。 ```cpp= #include <iostream> using namespace std; int main() { int n; while(cin >> n) { int ans = n; // 答案至少有 n 瓶 while(n >= 3) { // 如果 n 大於等於 3,還可以再換到新的可樂 ans += n/3; // ans 加上換來的可樂數量 n/3 n = n/3 + n%3; // 更新 n,n/3 是換來的數量,n%3 是剩下的數量 } if (n == 2) ans++; // 如果剩 2 瓶,可以借 1 個空瓶,ans 加 1 cout << ans << "\n"; // 印出答案 } return 0; } ``` --- ###### tags:`演算法`、`APCS`、`Python`、`C++`