2025年2月26日 星期三

ZeroJudge 解題筆記:f071. 2. 刮刮樂 (Lottery)

作者:王一哲
日期:2025年2月26日



ZeroJudge 題目連結:f071. 2. 刮刮樂 (Lottery)

解題想法


注意:同一個號碼可能出現不只一次,金額可能會有好幾個。因為號碼可能不連續,所以我用字典儲存號碼與對應的金額。

Python 程式碼


使用時間約為 27 ms,記憶體約為 3.4 MB,通過測試。
a, b, c = map(int, input().split())  # 幸運數字
key = list(map(int, input().split()))  # 號碼
val = list(map(int, input().split()))  # 金額
lottery = dict()  # {號碼: [金額]},同一個號碼可能出現不只一次,金額可能會有好幾個
for k, v in zip(key, val):  # 依序讀取 key 及 val
    if k not in lottery: lottery[k] = [v]  # 如果 k 不在 lottery 之中,對應的值為 [v]
    else: lottery[k].append(v)  # 如果 k 在 lottery 之中,對應的值加上 v
tot = 0  # 奬金
if a in lottery:  # 如果 a 在 lottery 之中,加上對應的金額
    for v in lottery[a]:
        tot += v
if b in lottery:  # 如果 b 在 lottery 之中,加上對應的金額
    for v in lottery[b]:
        tot += v
if c in lottery:  # 如果 c 在 lottery 之中,減去對應的金額
    for v in lottery[c]:
        tot -= v
else: tot *= 2  # 如果 c 不在 lottery 之中,tot 加倍
if tot < 0: tot = 0  # 如果 tot 為負值,歸零
print(tot)  # 印出答案


C++ 程式碼


使用時間約為 5 ms,記憶體約為 356 kB,通過測試。
#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int a, b, c; cin >> a >> b >> c;  // 幸運數字
    int key[5], val[5];  // 號碼,金額
    for(int i=0; i<5; i++) cin >> key[i];
    for(int i=0; i<5; i++) cin >> val[i];
    map<int, vector<int>> lottery;  // {號碼: [金額]},同一個號碼可能出現不只一次,金額可能會有好幾個
    for(int i=0; i<5; i++) lottery[key[i]].push_back(val[i]);  // 依序讀取 key 及 val,加到 lottery 之中
    int tot = 0;  // 奬金
    if (!lottery[a].empty()) {  // 如果 a 在 lottery 之中,加上對應的金額
        for(int v : lottery[a]) tot += v;
    }
    if (!lottery[b].empty()) {  // 如果 b 在 lottery 之中,加上對應的金額
        for(int v : lottery[b]) tot += v;
    }
    if (!lottery[c].empty()) {  // 如果 c 在 lottery 之中,減去對應的金額
        for(int v : lottery[c]) tot -= v;
    } else {
        tot *= 2;  // 如果 c 不在 lottery 之中,tot 加倍
    }
    if (tot < 0) tot = 0;  // 如果 tot 為負值,歸零
    cout << tot << "\n";  // 印出答案
    return 0;
}


沒有留言:

張貼留言