日期:2025年6月18日
ZeroJudge 題目連結:p901. 香料 (Spices)
解題想法
這題用字典儲存每個編號的香料在貨架上的位置,速度較慢但程式好寫。
Python 程式碼
使用時間約為 51 ms,記憶體約為 7.1 MB,通過測試。
import sys
for line in sys.stdin:
n = int(line) # n 個要找的香料
si = list(map(int, input().split())) # 要找的香料編號
r, c = map(int, input().split()) # 貨架 r*c
shelf = [list(map(int, input().split())) for _ in range(r)] # 貨架上的香料編號
table = dict() # 各編號香料的位置
for i in range(r): # 依序掃過貨架每一格
for j in range(c):
table[shelf[i][j]] = (i+1, j+1) # 題目的編號從 1 開始
for s in si: # 依序讀取要找的香料編號
if s not in table: print(-1) # 如果 s 不在 table 之中印出 -1
else: print(*table[s]) # 反之印出編號
使用時間約為 48 ms,記憶體約為 7 MB,通過測試。
import sys
for line in sys.stdin:
n = int(line) # n 個要找的香料
si = list(map(int, input().split())) # 要找的香料編號
r, c = map(int, input().split()) # 貨架 r*c
table = dict() # 各編號香料的位置
for i in range(1, r+1): # 依序掃過貨架每一格,題目的編號從 1 開始
for j, s in enumerate(map(int, input().split()), start=1):
table[s] = (i, j)
for s in si: # 依序讀取要找的香料編號
if s not in table: print(-1) # 如果 s 不在 table 之中印出 -1
else: print(*table[s]) # 反之印出編號
C++ 程式碼
使用時間約為 9 ms,記憶體約為 748 kB,通過測試。
#include <cstdio>
#include <unordered_map>
#include <utility>
using namespace std;
int main() {
int n; // n 個要找的香料
while(scanf("%d", &n) != EOF) {
int si[n]; // 要找的香料編號
for(int i=0; i<n; i++) scanf("%d", &si[i]);
int r, c; scanf("%d %d", &r, &c); // 貨架 r*c
unordered_map<int, pair<int, int>> table; // 各編號香料的位置
for(int i=1; i<=r; i++) { // 依序掃過貨架每一格
for(int j=1; j<=c; j++) {
int idx; scanf("%d", &idx); // 此格的香料編號
table[idx] = make_pair(i, j);
}
}
for(int i=0; i<n; i++) { // 依序讀取要找的香料編號
if (table.count(si[i]) == 0) printf("-1\n"); // 如果 si[i] 不在 table 之中印出 -1
else printf("%d %d\n", table[si[i]].first, table[si[i]].second); // 反之印出編號
}
}
return 0;
}
沒有留言:
張貼留言