日期:2025年2月28日
ZeroJudge 題目連結:f147. 1. 點餐系統 (Ordering System)
解題想法
如果使用 Python,可以把套餐、單點的名稱、價格,分別儲存在一個二維數組之中,也可以全部儲存在一個三維數組之中。但是 C++ 的陣列只能儲存相同格式的資料,如果想要全部儲存在同一個陣列之中,要自訂結構體才行。
Python 程式碼
把套餐、單點的名稱、價格,分別儲存在一個二維數組之中。使用時間約為 39 ms,記憶體約為 3.4 MB,通過測試。
combo = (("", 0), ("Medium Wac", 4), ("WChicken Nugget", 8),
("Geez Burger", 7), ("ButtMilk Crispy Chicken", 6), ("Plastic Toy", 3))
dish = (("", 0), ("German Fries", 2), ("Durian Slices", 3),
("WcFurry", 5), ("Chocolate Sunday", 7))
tot = 0 # 總金額
while True:
order = int(input()) # 讀取指令
if order == 0: # 當指令等於 0,印出總金額,中止迴圈
print(f"Total: {tot:d}")
break
num = int(input()) # 套餐或單點號碼
if order == 1:
print(f"{combo[num][0]:s} {combo[num][1]:d}")
tot += combo[num][1]
elif order == 2:
print(f"{dish[num][0]:s} {dish[num][1]:d}")
tot += dish[num][1]
把套餐、單點的名稱、價格,儲存在一個三維數組之中,可以將上方程式碼第12到17行合併。使用時間約為 28 ms,記憶體約為 3.3 MB,通過測試。
meal = ((()),
(("", 0), ("Medium Wac", 4), ("WChicken Nugget", 8),
("Geez Burger", 7), ("ButtMilk Crispy Chicken", 6), ("Plastic Toy", 3)),
(("", 0), ("German Fries", 2), ("Durian Slices", 3),
("WcFurry", 5), ("Chocolate Sunday", 7)))
tot = 0 # 總金額
while True:
order = int(input()) # 讀取指令
if order == 0: # 當指令等於 0,印出總金額,中止迴圈
print(f"Total: {tot:d}")
break
num = int(input()) # 套餐或單點號碼
print(f"{meal[order][num][0]:s} {meal[order][num][1]:d}")
tot += meal[order][num][1]
C++ 程式碼
使用時間約為 10 ms,記憶體約為 364 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string comboName[6] = {"", "Medium Wac", "WChicken Nugget", "Geez Burger",
"ButtMilk Crispy Chicken", "Plastic Toy"};
int comboPrice[6] = {0, 4, 8, 7, 6, 3};
string dishName[5] = {"", "German Fries", "Durian Slices", "WcFurry", "Chocolate Sunday"};
int dishPrice[5] = {0, 2, 3, 5, 7};
int tot = 0; // 總金額
while(true) {
int order; cin >> order; // 讀取指令
if (order == 0) { // 當指令等於 0,印出總金額,中止迴圈
cout << "Total: " << tot << "\n";
break;
}
int num; cin >> num; // 套餐或單點號碼
if (order == 1) {
cout << comboName[num] << " " << comboPrice[num] << "\n";
tot += comboPrice[num];
} else if (order == 2) {
cout << dishName[num] << " " << dishPrice[num] << "\n";
tot += dishPrice[num];
}
}
return 0;
}
沒有留言:
張貼留言