To solve this problem, we need to calculate the total price of a list of products based on their given prices.
Approach
- Read Product Prices: First, we read lines that contain product names and their corresponding prices. We store these in a dictionary where the key is the product name and the value is the price.
- Calculate Total Cost: Next, we read lines that list the products to be purchased. For each product in this list, we look up its price from the dictionary and add it to the total cost.
Solution Code
product_prices = {}
total = 0
import sys
for line in sys.stdin:
line = line.strip()
if not line:
continue
parts = line.split()
if len(parts) == 2:
# Add product and price to the dictionary
product = parts[0]
price = int(parts[1])
product_prices[product] = price
elif len(parts) == 1:
# Add the price of the product to the total
product = parts[0]
total += product_prices[product]
print(total)
Explanation
- Reading Product Prices: The code reads each line from the input. Lines with two parts (product name and price) are stored in a dictionary. This allows O(1) lookups for product prices later.
- Calculating Total: Lines with a single part (product name) are considered as items to purchase. For each such product, we retrieve its price from the dictionary and add it to the total cost.
- Efficiency: The approach efficiently handles the input and computes the total cost in linear time relative to the number of input lines, making it optimal for the given problem constraints.
This solution is straightforward and ensures that we correctly compute the total price of the desired products. It handles multiple occurrences of the same product in the shopping list by adding the price each time the product appears.


作者声明:本文包含人工智能生成内容。