日期:2025年2月12日
ZeroJudge 題目連結:e839. P6. 飲食分類 (Food)
解題想法
這題用字典儲存各種類食物的名稱會比較方便。
Python 程式碼
使用預設的字典儲存食物名稱、種類。使用時間約為 19 ms,記憶體約為 3.3 MB,通過測試。
n = int(input()) # n 個食物
food = dict() # 食物種類、名稱
for _ in range(n): # 讀取 n 行資料
f, s = input().split() # 食物名稱 f、種類 s
if s not in food: food[s] = [f] # 如果 s 不在 food 之中,food[s] 設定為 [f]
else: food[s].append(f) # 如果 s 已經在 food 之中,food[s] 新增 f
t = input().strip() # 要找的目標
if t not in food: print("No") # 如果 t 不在 food 之中,印出 No
else: # 如果 t 在 food 之中,將食物名稱排序後印出
for f in sorted(food[t]):
print(f)
改用 collections.defaultdict。使用時間約為 22 ms,記憶體約為 3.6 MB,通過測試。
from collections import defaultdict
n = int(input()) # n 個食物
food = defaultdict(list) # 食物種類、名稱
for _ in range(n): # 讀取 n 行資料
f, s = input().split() # 食物名稱 f、種類 s
food[s].append(f) # food[s] 新增 f
t = input().strip() # 要找的目標
if t not in food: print("No") # 如果 t 不在 food 之中,印出 No
else: # 如果 t 在 food 之中,將食物名稱排序後印出
for f in sorted(food[t]):
print(f)
C++ 程式碼
使用時間約為 2 ms,記憶體約為 356 kB,通過測試。
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n; cin >> n; // n 個食物
map<string, vector<string>> food; // 食物種類、名稱
for(int i=0; i<n; i++) { // 讀取 n 行資料
string f, s; cin >> f >> s; // 食物名稱 f、種類 s
food[s].push_back(f); // food[s] 新增 f
}
string t; cin >> t; // 要找的目標
if (food[t].empty()) cout << "No\n"; // 如果 t 不在 food 之中,印出 No
else { // 如果 t 在 food 之中,將食物名稱排序後印出
vector<string> fo = food[t];
sort(fo.begin(), fo.end());
for(string f : fo) cout << f << "\n";
}
return 0;
}
沒有留言:
張貼留言