ZeroJudge F579: Shopping Cart

You're given two integers, A and B, representing the product numbers you want to observe.

The mall has placed a sensor in each customer's shopping cart, which can detect when a customer adds or removes items from the cart. The records stored by the sensor are a series of integers. A positive integer x indicates that the customer has added an item with the number x to their cart, while a negative integer -x indicates that the customer has removed an item with the number x from their cart.

Now there are records of N customers' shopping carts. You want to count how many customers ultimately purchased both products A and B. A customer is considered to have purchased a product X if the number of times the product X was added to their cart is greater than the number of times it was removed.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
The first line contains two positive integers A and B
(1 <= A, B <= 100).
The second line contains a positive integer N (1 <= N <= 100), indicating the number of customers.
Following that are N lines, where the i-th line represents the shopping cart records of the i-th customer.
Each shopping cart record consists of a series of integers, with the last number always being 0, indicating the end of the shopping record. Other numbers are non-zero integers and their absolute values do not exceed 100, as defined in the problem statement.
Output an integer, indicating how many customers simultaneously purchased both products A and B.
1 8
5
1 8 0
5 6 0
2 7 0
8 1 0
33 22 0
2
3 9
2
3 9 -3 3 9 0
3 3 -3 -3 9 0
1

Thought Process

When collecting shopping cart data, you can use EOF. You can use a Map to record the addition and removal of products. If a product is added, increment its count by 1; if it's removed, decrement its count by 1.

After collecting the data from each person, you can check if the counts of products A and B in the Map are greater than 0. If both products A and B are purchased by a customer, increment the answer by 1.

Sample Code-ZeroJudge F579: Shopping Cart

#include <iostream>
#include <map>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int a, b;
    cin >> a >> b;
    int N;
    cin >> N;
    int ans = 0;
    for (int i = 0; i<N; i++)
    {
        int tmp;
        map<int, int>MAP;
        while (cin >> tmp && tmp != 0)
        {
            if (tmp > 0) MAP[tmp]++;
            else MAP[tmp*-1]--;
        }
        if (MAP[a] > 0 && MAP[b] > 0) ans++;
    }
    cout << ans << "\n";
}

//ZeroJudge F579
//Dr. SeanXD

Comments