To solve this problem, we need to compute the total cost for a list of transactions based on a secret price list. The secret price list contains items with multiple prices, and the price used for each transaction depends on the quantity of the item purchased. If the quantity exceeds the number of available prices, the highest price is used.
-
Parse the Secret Price List:
- Read the number of items.
- For each item, split the line into the item name and its prices. Convert the prices into a list of integers.
- Store the item and its prices in a dictionary for quick lookup.
-
Process Transactions:
- Read the number of transactions.
- For each transaction, split the line into the item name and the quantity.
- Retrieve the prices for the item from the dictionary.
- Determine the price to use:
- If the quantity is within the range of the prices list, use the price at the index
quantity - 1. - If the quantity exceeds the list length, use the last price in the list.
- If the quantity is within the range of the prices list, use the price at the index
- Accumulate the total cost for all transactions.
Solution Code
def main():
import sys
data = sys.stdin.read().splitlines()
if not data:
print(0)
return
n = int(data[0].strip())
prices_dict = {}
index = 1
for _ in range(n):
parts = data[index].split(':', 1)
index += 1
item_name = parts[0].strip()
prices_str = parts[1].strip()
prices_list = list(map(int, prices_str.split()))
prices_dict[item_name] = prices_list
m = int(data[index].strip())
index += 1
total_cost = 0
for _ in range(m):
trans = data[index].split()
index += 1
item_name = trans[0]
quantity = int(trans[1])
prices = prices_dict[item_name]
if quantity <= len(prices):
price = prices[quantity - 1]
else:
price = prices[-1]
total_cost += price
print(total_cost)
if __name__ == "__main__":
main()
Explanation
- Reading Input: The input is read all at once for efficiency, especially given the constraints.
- Parsing the Secret Price List:
The first line indicates the number of items. Each subsequent line is split into the item name and its prices. The prices are converted into a list of integers and stored in a dictionary with the item name as the key.
- Processing Transactions:
- The next line after the price list gives the number of transactions. Each transaction line is split into the item name and quantity.
- For each item, the corresponding prices list is retrieved. The price is selected based on the quantity:
- If the quantity is within the bounds of the prices list, the price at the calculated index is used.
- If the quantity is larger, the last price in the list is used.
- The selected price is added to the total cost.
- Output: The accumulated total cost is printed after processing all transactions.
This approach efficiently handles the input and processes each transaction by leveraging dictionary lookups and conditional checks to determine the correct price, ensuring optimal performance.
Request an On-site Audit / Inquiry