日期:2025年9月12日
ZeroJudge 題目連結:d710. parking lot
解題想法
這題用字典儲存資料很方便,一個儲存廠牌對應的顏色,另一個儲存顏色對應的廠牌,最後再依照測資從字典中讀取資料並輸出。
Python 程式碼
使用時間約為 23 ms,記憶體約為 3.6 MB,通過測試。
import sys
from collections import defaultdict
for line in sys.stdin:
if not line.strip(): continue # 跳過空行
n, m = map(int, line.split()) # n 輛車, m 個指示
brands = defaultdict(list) # 廠牌對應的顏色
colors = defaultdict(list) # 顏色對應的廠牌
for _ in range(n): # 讀取 n 行資料
b, c = input().split() # 廠牌 b,顏色 c
brands[b].append(c)
colors[c].append(b)
for _ in range(m): # 讀取 m 個指示
x, y = input().split()
if x == "brand": # 如果 x 等於 brand
for c in brands[y]: # 依序取出 brands[y] 的顏色
print(f"{y:s} {c:s}")
elif x == "color": # 如果 x 等於 color
for b in colors[y]: # 依序取出 colors[y] 的廠牌
print(f"{b:s} {y:s}")
print() # 空一行
C++ 程式碼
使用時間約為 2 ms,記憶體約為 348 kB,通過測試。
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, m; // n 輛車, m 個指示
unordered_map<string, vector<string>> brands, colors; // 廠牌對應的顏色,顏色對應的廠牌
while(cin >> n >> m) {
brands.clear(); colors.clear(); // 清空資料
for(int i=0; i<n; i++) { // 讀取 n 行資料
string b, c; cin >> b >> c; // 廠牌 b,顏色 c
brands[b].push_back(c);
colors[c].push_back(b);
}
for(int i=0; i<m; i++) { // 讀取 m 個指示
string x, y; cin >> x >> y;
if (x == "brand") { // 如果 x 等於 brand
for(auto c : brands[y]) { // 依序取出 brands[y] 的顏色
cout << y << " " << c << "\n";
}
} else if (x == "color") { // 如果 x 等於 color
for(auto b : colors[y]) { // 依序取出 colors[y] 的廠牌
cout << b << " " << y << "\n";
}
}
}
cout << "\n"; // 空一行
}
return 0;
}
沒有留言:
張貼留言