【題解】ZeroJudge f579: 1. 購物車

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=f579
【注意】

  • xi 與 -xi 為相同的物品。
  • 當購物車中無任何 xi 物品時,輸入 -xi 並不會使 xi 的個數變成負值。
#include <iostream>
#include <map>
using namespace std;

int main() {
    int a, b, n, x, ans=0;
        map<int,int> mp;
        cin >> a >> b >> n;
        for (int i=0; i<n; i++){
            mp.clear();
            while (1){
                cin >> x;
                if (x > 0){
                    mp[x]++;
                }else if (x < 0){
                    if (mp[-x] > 0){
                        mp[-x]--;
                    }
                }else{
                    break;
                }
            }
            if (mp[a] && mp[b]){
                ans+= 1;
            }
        }
        cout << ans << "\n";
}

Python code (credit: Amy Chou)

a, b = map(int, input().split())
n = int(input())
cart = [dict() for _ in range(n)]
for i in range(n):
    lst = list(map(int, input().split()))
    for j in lst[:-1]:
        if j > 0:
            cart[i][j] = cart[i].get(j, 0) + 1
        else:
            cart[i][abs(j)] = max(cart[i].get(abs(j), 0) - 1, 0)

ans = 0
for i in range(n):
    flag_a = cart[i].get(a, 0) > 0
    flag_b = cart[i].get(b, 0) > 0
    ans += flag_a and flag_b
print(ans)
分享本文 Share with friends