The city of Hakodate recently established a commodity exchange market. To participate in the market, each dealer transmits through the Internet an order consisting of his or her name, the type of the order (buy or sell), the name of the commodity, and the quoted price.
In this market a deal can be made only if the price of a sell order is lower than or equal to the price of a buy order. The price of the deal is the mean of the prices of the buy and sell orders, where the mean price is rounded downward to the nearest integer. To exclude dishonest deals, no deal is made between a pair of sell and buy orders from the same dealer. The system of the market maintains the list of orders for which a deal has not been made and processes a new order in the following manner.
For a new sell order, a deal is made with the buy order with the highest price in the list satisfying the conditions. If there is more than one buy order with the same price, the deal is made with the earliest of them.
For a new buy order, a deal is made with the sell order with the lowest price in the list satisfying the conditions. If there is more than one sell order with the same price, the deal is made with the earliest of them.
The market opens at 7:00 and closes at 22:00 everyday. When the market closes, all the remaining orders are cancelled. To keep complete record of the market, the system of the market saves all the orders it received everyday.
The manager of the market asked the system administrator to make a program which reports the activity of the market. The report must contain two kinds of information. For each commodity the report must contain informationon the lowest, the average and the highest prices of successful deals. For each dealer, the report must contain information on the amounts the dealer paid and received for commodities.
Input
The input contains several data sets. Each data set represents the record of the market on one day. The first line of each data set contains an integer n (n < 1000) which is the number of orders in the record. Each line of the record describes an order, consisting of the name of the dealer, the type of the order, the name of the commodity, and the quoted price. They are separated by a single space character.
The name of a dealer consists of capital alphabetical letters and is less than 10 characters in length. The type of an order is indicated by a string, "BUY" or "SELL". The name of a commodity is a single capital letter. The quoted price is a positive integer less than 1000.
The orders in a record are arranged according to time when they were received and the first line of the record corresponds to the oldest order.
The end of the input is indicated by a line containing a zero.
Output
The output for each data set consists of two parts separated by a line containing two hyphen (`-') characters.
The first part is output for commodities. For each commodity, your program should output the name of the commodity and the lowest, the average and the highest prices of successful deals in one line. The name and the prices in a line should be separated by a space character. The average price is rounded downward to the nearest integer. The output should contain only the commodities for which deals are made and the order of the output must be alphabetic.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The second part is output for dealers. For each dealer, your program should output the name of the dealer, the amounts the dealer paid and received for commodities. The name and the numbers in a line should be separated by a space character. The output should contain all the dealers who transmitted orders. The order of dealers in the output must be lexicographic on their names. The lexicographic order is the order in which words in dictionaries are arranged.
The output for each data set should be followed by a linecontaining ten hyphen (`-') characters.
Example
Input
3
PERLIS SELL A 300
WILKES BUY A 200
HAMMING SELL A 100
4
BACKUS SELL A 10
FLOYD BUY A 20
IVERSON SELL B 30
BACKUS BUY B 40
7
WILKINSON SELL A 500
MCCARTHY BUY C 300
WILKINSON SELL C 200
DIJKSTRA SELL B 100
BACHMAN BUY A 400
DIJKSTRA BUY A 600
WILKINSON SELL A 300
2
ABCD SELL X 10
ABC BUY X 15
2
A SELL M 100
A BUY M 100
0
We need to process orders in sequence and match orders according to rules.
Interpretation:
For a new SELL order: try to match with the highest buy price among open buy orders (i.e., orders not yet matched) that satisfy:
buy order's commodity == sell's commodity,
buy price >= sell price (since deal occurs if sell price <= buy price). Actually condition: "a deal can be made only if the price of a sell order is lower than or equal to the price of a buy order." So sell price <= buy price. So when processing a sell, we look for a buy order with highest price among those that have price >= sell price, and same commodity, and not same dealer (no deal if same dealer). If multiple same highest price, pick earliest (i.e., the one with smallest time stamp among those).
For a new BUY order: try to match with the lowest sell price among open sell orders that satisfy:
same commodity,
sell price <= buy price (i.e., sell price <= buy price), but we can also see: condition is sell price <= buy price. So when processing a buy, we look for the sell order with lowest price among those that have price <= buy price, same commodity, different dealer. If multiple with same lowest price, pick earliest.
Once matched, we remove both orders from open lists. The deal price is the mean of the two quoted prices (buy price and sell price), rounded down to nearest integer (floor). So floor((buy_price + sell_price)/2).
The order list: we have n orders, each with dealer name, type, commodity (single letter), price. They are given in order of time.
We need to output two parts.
First part: For each commodity that has at least one deal, output: commodity name, lowest deal price (among deals for that commodity), average (floor of average of all deal prices? The problem says: "the average price is rounded downward to the nearest integer." So we compute the sum of all deal prices for that commodity, divided by number of deals, floor. So integer division rounding down. Highest deal price. Output in alphabetical order of commodity.
Second part: For each dealer (anyone who transmitted orders, i.e., appears in order list), we output: dealer name, amount paid, amount received. The amounts: "the amounts the dealer paid and received for commodities." I interpret: For each dealer, we compute total money they spent (paid) and total money they received (received). When a dealer buys a commodity, they pay the deal price (they give money to the seller). So that amount is added to their paid amount. When a dealer sells a commodity, they receive the deal price (they receive money from the buyer). So that amount is added to their received amount.
Important: For a deal, both parties have opposite roles. So for the seller: received += deal_price; for the buyer: paid += deal_price.
We need to output all dealers (including those who did not participate in any deal; they have 0 for both). The order is lexicographic (i.e., dictionary order). We need to output all distinct dealer names.
Note: There might be multiple orders from the same dealer. Also, there is the restriction: "To exclude dishonest deals, no deal is made between a pair of sell and buy orders from the same dealer." So we must check that dealer names differ.
Processing: We maintain open orders for each commodity separately? Since matching only across same commodity. So we can maintain for each commodity: list of open sell orders and open buy orders. But matching also involves picking the best order according to price and time. Since orders are processed sequentially, we need to efficiently select from all open orders of opposite type for that commodity. n < 1000, small. So we can just keep lists and linear scan each time. But careful: When a new order arrives, we need to find a matching order among the opposite type orders that satisfy conditions (same commodity, price condition, different dealer) and choose according to rules (highest price for sell, or lowest price for sell). Since n is small, O(n^2) is fine (max 1000 orders, each scanning up to maybe 1000 open orders). So simpler to keep all open orders in a list.
Better: For each commodity, maintain two priority queues or sorted lists? But with 1000 orders, we can implement as simple loops.
Algorithm:
Initialize:
open_sells = [] (list of orders that are sell and not matched, each order has fields: dealer, commodity, price, order_index (time order))
open_buys = [] (similar)
deals = [] list of deals: each deal includes commodity, price, buyer, seller.
For each order in sequence (index i from 0 to n-1):
parse: dealer, typ, commodity, price (int)
If typ == "SELL":
candidate = None
best_buy = None
For each buy in open_buys:
if buy.commodity == commodity and buy.price >= price and buy.dealer != dealer:
# qualify
if best_buy is None or buy.price > best_buy.price or (buy.price == best_buy.price and buy.index < best_buy.index):
best_buy = buy
If best_buy found:
# match
deal_price = (price + best_buy.price) // 2 # floor integer division
record deal: commodity, deal_price, seller = dealer, buyer = best_buy.dealer
Update dealer totals:
seller_received += deal_price
buyer_paid += deal_price
Remove best_buy from open_buys.
# The current sell order is not added to open_sells because it's matched immediately.
else:
# No matching buy; add this sell to open_sells.
add to open_sells with index = i.
else if typ == "BUY":
candidate_sell = None
For each sell in open_sells:
if sell.commodity == commodity and sell.price <= price and sell.dealer != dealer:
if candidate_sell is None or sell.price < candidate_sell.price or (sell.price == candidate_sell.price and sell.index < candidate_sell.index):
candidate_sell = sell
If candidate_sell found:
deal_price = (price + candidate_sell.price) // 2
record deal: commodity, deal_price, seller = candidate_sell.dealer, buyer = dealer
Update totals:
seller_received += deal_price
buyer_paid += deal_price
Remove candidate_sell from open_sells.
# current buy not added.
else:
add to open_buys with index = i.
After processing all orders, we have deals list and totals per dealer (init with 0). We also need to handle dealers that only have orders but no deals; they are already in totals map if we initialized when encountered orders. We can maintain a dictionary dealer_info: mapping name -> [paid, received] (both ints). Initially set both to 0. For each order we could also ensure the dealer is added to map. Then when a deal happens, update both parties.
Now output.
First part: For each commodity, gather deal prices. We can maintain a dict commodity_deals: mapping commodity -> list of deal prices. After processing, for each commodity with non-empty list:
min_price = min(list)
max_price = max(list)
avg_price = floor(sum(list) / len(list)) # integer division (floor)
We need to output in alphabetical order of commodity. So sort keys.
Second part: For each dealer, get paid and received. Output in lexicographic order.
Between the two parts, output a line containing two hyphens: "--". And after the data set output, a line of ten hyphens: "----------".
Note: The output format in example:
A 150 150 150
HAMMING 0 150
PERLIS 0 0
WILKES 150 0
Observe that the first part might be empty if no deals? In example, they show a dataset where no deals? In input there is:
2
A SELL M 100
A BUY M 100
This dataset: two orders from same dealer A. They are a sell and a buy for same commodity, but same dealer, so no deal. Also note the buy price=100, sell price=100, but since same dealer, no deal. So open orders: first sell (A SELL M 100) -> no matching buy, add to sells. Then buy (A BUY M 100) -> find matching sell? Check condition: sell.commodity=M, sell.price <= buy.price (100 <= 100) true, but dealer same (A == A) so not allowed. So no match. So no deals. The output shows:
--
A 0 0
So first part is empty (just the line "--" immediately?) Actually the example output for that dataset:
--
A 0 0
So they output the two hyphens line, but with no lines before it. That means if there are no commodities with deals, then the first part has no lines, and then we output "--". That's fine.
Similarly, if there are no dealers? But at least one dealer appears because there are orders. But possible if n=0? But n is positive in dataset? The input contains a line with 0 to stop, so n>0 for datasets. So at least one dealer.
So algorithm is straightforward.
Edge cases:
When matching, if there are multiple candidates with same price, choose the earliest (i.e., smallest index). So we need to store the order index (original sequence number) with each open order. So we can compare indices.
When matching, we must ensure the dealer is different. That's checked.
Possibly multiple orders from same dealer for same commodity, and we may match later with another order from the same dealer? Should be prevented.
The price condition: For a new sell order, we require buy order's price >= sell's price. For a new buy order, require sell order's price <= buy's price. So essentially same condition.
The matching rule for new sell: "deal is made with the buy order with the highest price in the list satisfying the conditions. If there is more than one buy order with the same price, the deal is made with the earliest of them." So we choose the highest price among all qualifying buys. That's what we do.
For new buy: "deal is made with the sell order with the lowest price in the list satisfying the conditions. If there is more than one sell order with the same price, the deal is made with the earliest of them." So we choose the lowest price among qualifying sells.
Implementation details:
We'll parse each dataset until n=0.
Pseudo:
while True:
line = input().strip()
if line == '': continue? But typical.
n = int(line)
if n == 0: break
orders = []
for _ in range(n):
parts = input().split()
dealer = parts[0]
typ = parts[1]
commodity = parts[2]
price = int(parts[3])
orders.append((dealer, typ, commodity, price))
code
# processing
open_sells = [] # each: (index, dealer, commodity, price)
open_buys = []
deals = [] # (commodity, price, seller, buyer)
dealer_totals = {} # dealer -> [paid, received] (initialize when first encountered)
for i, (dealer, typ, commodity, price) in enumerate(orders):
# ensure dealer in totals
if dealer not in dealer_totals:
dealer_totals[dealer] = [0, 0] # [paid, received]
if typ == "SELL":
# find best buy
best_buy = None
best_buy_idx = -1
for j, buy in enumerate(open_buys):
b_idx, b_dealer, b_comm, b_price = buy
if b_comm == commodity and b_price >= price and b_dealer != dealer:
if best_buy is None or b_price > best_buy[3] or (b_price == best_buy[3] and b_idx < best_buy[0]):
best_buy = buy
best_buy_idx = j
if best_buy is not None:
b_idx, b_dealer, b_comm, b_price = best_buy
deal_price = (price + b_price) // 2
deals.append((commodity, deal_price, dealer, b_dealer))
# update totals
dealer_totals[dealer][1] += deal_price # seller receives
dealer_totals[b_dealer][0] += deal_price # buyer pays
# remove matched buy from open_buys
del open_buys[best_buy_idx]
# do not add this sell
else:
open_sells.append((i, dealer, commodity, price))
else: # BUY
best_sell = None
best_sell_idx = -1
for j, sell in enumerate(open_sells):
s_idx, s_dealer, s_comm, s_price = sell
if s_comm == commodity and s_price <= price and s_dealer != dealer:
if best_sell is None or s_price < best_sell[3] or (s_price == best_sell[3] and s_idx < best_sell[0]):
best_sell = sell
best_sell_idx = j
if best_sell is not None:
s_idx, s_dealer, s_comm, s_price = best_sell
deal_price = (price + s_price) // 2
deals.append((commodity, deal_price, s_dealer, dealer))
dealer_totals[s_dealer][1] += deal_price
dealer_totals[dealer][0] += deal_price
del open_sells[best_sell_idx]
else:
open_buys.append((i, dealer, commodity, price))
# Now produce output
# Build commodity data
comm_prices = {}
for (comm, price, seller, buyer) in deals:
if comm not in comm_prices:
comm_prices[comm] = []
comm_prices[comm].append(price)
# First part: commodities
output_lines = []
if comm_prices:
for comm in sorted(comm_prices.keys()):
prices = comm_prices[comm]
low = min(prices)
high = max(prices)
avg = sum(prices) // len(prices) # floor division
output_lines.append(f"{comm} {low} {avg} {high}")
# else, no lines
# Add the separator line: --
output_lines.append("--")
# Second part: dealers
for dealer in sorted(dealer_totals.keys()):
paid, received = dealer_totals[dealer]
output_lines.append(f"{dealer} {paid} {received}")
# Add the ten hyphens line
output_lines.append("----------")
# Print
print("\n".join(output_lines))
But check example output: For first dataset:
3 orders:
PERLIS SELL A 300 -> open_sells: (0, PERLIS, A, 300)
WILKES BUY A 200 -> new BUY: price 200, commodity A. Check open_sells: sell (PERLIS, A, 300) but sell.price=300 <= 200? No, condition sell.price <= buy.price fails. So no match. So open_buys: (1, WILKES, A, 200)
HAMMING SELL A 100 -> new SELL: price 100, commodity A. Check open_buys: buy (WILKES, A, 200) price 200 >=100, dealer different. So match. deal_price = (100+200)//2 = 150. So deal: A 150, seller HAMMING, buyer WILKES.
Then open_buys becomes empty. open_sells still has PERLIS (0) but no more orders.
Deals: only one deal. So commodity A: low=150, high=150, avg=150. So output "A 150 150 150". Dealers: HAMMING: paid 0, received 150; PERLIS: paid 0, received 0; WILKES: paid 150, received 0. Sorted lexicographically: HAMMING, PERLIS, WILKES. That matches.
Second dataset:
4 orders:
BACKUS SELL A 10 -> open_sells: (0, BACKUS, A,10)
FLOYD BUY A 20 -> buy: price 20, A. Check sells: (BACKUS, A, 10) price <=20, dealer diff -> match. deal_price=(10+20)//2=15. seller BACKUS receives 15, buyer FLOYD pays 15. open_sells empty.
IVERSON SELL B 30 -> open_sells: (2, IVERSON, B,30)
BACKUS BUY B 40 -> buy: price 40, B. Check sells: (IVERSON,B,30) price 30<=40, dealer diff -> match. deal_price=(30+40)//2=35. seller IVERSON receives 35, buyer BACKUS pays 35.
Deals: A: 15; B: 35. So output: A 15 15 15, B 35 35 35. Dealers: BACKUS (appears twice: first as seller, later as buyer) totals: Received from first deal: 15, Paid in second deal: 35. So net: Paid=35, Received=15 -> output "BACKUS 35 15". FLOYD: Paid=15, Received=0. IVERSON: Paid=0, Received=35. Sorted: BACKUS, FLOYD, IVERSON. Matches example.
Third dataset:
7 orders:
Let's simulate to confirm:
WILKINSON SELL A 500 -> open_sells: (0, WILKINSON, A,500)
MCCARTHY BUY C 300 -> open_buys: (1, MCCARTHY, C,300)
WILKINSON SELL C 200 -> open_sells: now also (2, WILKINSON, C,200)
DIJKSTRA SELL B 100 -> open_sells: (3, DIJKSTRA, B,100)
BACHMAN BUY A 400 -> buy: A 400. Check open_sells for A: only (0, WILKINSON, A,500) price 500 <= 400? No. So no match. Add to open_buys: (4, BACHMAN, A,400)
DIJKSTRA BUY A 600 -> buy: A 600. Check open_sells for A: (0, WILKINSON, A,500) price 500 <=600, dealer diff -> qualifies. Also maybe there is no other sells for A. So we choose the lowest price among qualifying sells. Only sell is 500, it's the lowest. So match. deal_price = (500+600)//2 = 550. seller: WILKINSON, buyer: DIJKSTRA. Update: WILKINSON receives 550, DIJKSTRA pays 550. Remove sell (0) from open_sells.
Now open_buys: (1, MCCARTHY, C,300), (4, BACHMAN, A,400). open_sells: (2, WILKINSON, C,200), (3, DIJKSTRA, B,100). Also note we have just added a new buy order? Actually order 6 is processed and matched, so not added.
WILKINSON SELL A 300 -> sell: A 300. Now check open_buys for A: (4, BACHMAN, A,400) price 400 >=300 and dealer diff (WILKINSON vs BACHMAN) -> qualifies. Are there any other buys for A? No. So match. deal_price = (300+400)//2 = 350. seller: WILKINSON receives 350, buyer: BACHMAN pays 350. Remove buy (4) from open_buys.
Now open_buys: (1, MCCARTHY, C,300). open_sells: (2, WILKINSON, C,200), (3, DIJKSTRA, B,100). After processing all orders, no more matches? But note that there is still a sell for C (WILKINSON 200) and a buy for C (MCCARTHY 300) from earlier that haven't matched. Why didn't they match? The buy was added earlier, and the sell was added after. But the sell order (2) was added at step 3. Then the buy (1) was already there at step 2. When the sell order was added at step 3, we processed it as a new sell: we looked for a buy with highest price among those with price >= sell.price. At that time, there was open buy (1, MCCARTHY, C,300) with price 300 >=200, dealer diff -> qualifies. So why didn't they match at step 3? Let's see step 3: order: WILKINSON SELL C 200. At that moment, open_buys has only (1, MCCARTHY, C,300). So it should have matched then. But wait, the example output shows a deal for C with price 250? In the output we see "C 250 250 250". That indicates there is a deal for C. But in my simulation, I said open_sells added (2) and open_buys (1) remained, but they should have matched at step 3. Let's check the example: The orders are:
7
WILKINSON SELL A 500
MCCARTHY BUY C 300
WILKINSON SELL C 200
DIJKSTRA SELL B 100
BACHMAN BUY A 400
DIJKSTRA BUY A 600
WILKINSON SELL A 300
At step 3: WILKINSON SELL C 200. There is an open buy from MCCARTHY for C at price 300. According to rules, for a new sell order, it matches with the highest price buy that satisfies conditions. That is MCCARTHY. The prices: sell 200, buy 300 -> deal price = 250. So they should match, and then that buy would be removed. But then later at step 6, we had DIJKSTRA BUY A 600, and at step 7, WILKINSON SELL A 300. The example output shows deals: A 350 450 550 (meaning there are at least two deals for A? Actually numbers: 350, 550? And average 450 suggests sum/2? 350+550 = 900, avg floor 450. So there are two deals for A: one at 550 and one at 350. And C 250. So there is a deal for C at 250. So my earlier step-by-step missed that match at step 3 because I incorrectly thought the sell was added without matching. Actually in my simulation I didn't process step 3 correctly: I said "open_sells: now also (2, WILKINSON, C,200)" but I should have checked if it matches. I missed that. So the correct sequence:
1: sell A 500 -> open_sells: (0, WILKINSON, A,500)
2: buy C 300 -> open_buys: (1, MCCARTHY, C,300)
3: sell C 200 -> new sell C 200. Check open_buys: buy (1) qualifies (price 300>=200, dealer diff). So match -> deal price = (200+300)//2 = 250. Record C deal: seller WILKINSON, buyer MCCARTHY. Update totals: WILKINSON receives 250, MCCARTHY pays 250. Remove buy (1) from open_buys. So open_buys becomes empty. This sell is not added.
4: sell B 100 -> open_sells: now has (0, WILKINSON, A,500) and new (3, DIJKSTRA, B,100)? Actually index: orders index: 0,1,2,3,... So step 4: DIJKSTRA SELL B 100 -> open_sells add (3, DIJKSTRA, B,100). So open_sells: (0, WILKINSON, A,500) and (3, DIJKSTRA, B,100). (note index 3)
5: buy A 400 -> BACHMAN BUY A 400. Check open_sells for A: (0, WILKINSON, A,500) price 500 <= 400? No. So no match. So open_buys add (4, BACHMAN, A,400).
6: buy A 600 -> DIJKSTRA BUY A 600. Check open_sells for A: (0, WILKINSON, A,500) qualifies (500 <=600, dealer diff). Also perhaps other sells? None. So match -> deal price = (500+600)//2=550. Seller: WILKINSON, buyer: DIJKSTRA. Update: WILKINSON receives 550, DIJKSTRA pays 550. Remove sell (0). open_sells now: (3, DIJKSTRA, B,100). open_buys: (4, BACHMAN, A,400).
7: sell A 300 -> WILKINSON SELL A 300. Check open_buys: (4, BACHMAN, A,400) qualifies (400>=300, dealer diff). So match -> deal price = (300+400)//2=350. Seller: WILKINSON, buyer: BACHMAN. Update: WILKINSON receives 350, BACHMAN pays 350. Remove buy (4). open_buys empty.
Now deals: C 250, A 550, A 350. So for A: prices 550 and 350 -> min 350, max 550, sum 900, avg 450 (floor). C: min 250, max 250, avg 250. No deals for B. So output matches example.
In dealer totals:
BACHMAN: paid 350, received 0.
DIJKSTRA: paid 550, received 0 (since also had a sell B 100? But that sell was not matched because no buy for B. So DIJKSTRA's sell B 100 never matched, so no receipt. DIJKSTRA also had buy A 600, matched, so pays 550. So total paid 550, received 0.)
MCCARTHY: paid 250, received 0.
WILKINSON: as seller for C 250, A 550, A 350: total received = 250+550+350 = 1150, paid 0.
Sorted lexicographically: BACHMAN, DIJKSTRA, MCCARTHY, WILKINSON. That matches example.
Great.
Now fourth dataset:
2
ABCD SELL X 10
ABC BUY X 15
Processing:
1: ABCD SELL X 10 -> open_sells: (0, ABCD, X,10)
2: ABC BUY X 15 -> check open_sells: (0, ABCD, X,10) price 10 <=15, dealer diff -> match. deal_price=(10+15)//2=12. Seller ABCD receives 12, buyer ABC pays 12.
Output: X 12 12 12. Dealers: ABC paid 12, received 0; ABCD paid 0, received 12. Sorted: ABC, ABCD. Matches example.
Fifth dataset:
2
A SELL M 100
A BUY M 100
1: A SELL M 100 -> open_sells: (0, A, M,100)
2: A BUY M 100 -> check open_sells: (0, A, M,100) price 100 <=100, but dealer same -> not allowed. So no match. open_buys: (1, A, M,100)
No deals. So commodity list empty. Dealers: A: paid 0, received 0.
Output: first part empty, then "--", then "A 0 0", then "----------". The example shows exactly that.
Thus algorithm is correct.
Now we need to produce output exactly as described. Note that in example the ten hyphens line is exactly ten hyphens. Also there is a blank line between datasets? The example output shows each dataset output separated by line with ten hyphens and then presumably next dataset. But after the ten hyphens there may be no extra blank line. The problem statement says "The output for each data set should be followed by a line containing ten hyphen (`-') characters." So after each dataset, we print that line. Typically there is no extra blank line between datasets. So we output as we have.
One more nuance: The input may have multiple spaces? But we can split by whitespace.
Edge Cases: When matching, we must ensure that we consider only open orders that are not yet matched. We are removing when matched. Good.
Potential tricky point: When there are multiple candidates with the same price, we need to pick the earliest (lowest index). Our comparison should be: for sell matching, choose buy with highest price; if ties, smallest index. So condition: if best_buy is None or (b_price > best_price) or (b_price == best_price and b_idx < best_idx). For buy matching: if best_sell is None or (s_price < best_price) or (s_price == best_price and s_idx < best_idx).
Works.
Now confirm the totals: For a dealer who appears multiple times in deals, we sum correctly.
Now check if any dealer might appear as both buyer and seller in different deals, they will have both paid and received.
Now, the output order for dealers: lexicographic order. In Python, sorting strings gives lexicographic order based on Unicode code points. Since names are capital letters only, fine.
Now consider possible pitfalls: In some languages, "lexicographic order" might be the same as string order. Good.
Now what about when there is no deal for any commodity? The first part should have no lines, then immediately the "--" line. In our code, we build output_lines as list; if comm_prices empty, we just output "". But we need to print the "--" line anyway. So output_lines after building commodity lines includes "--". Good. But if there are no commodity lines, then output_lines initially empty, we add "--", then dealer lines, then ten hyphens. So the first line printed is "--". That matches example: they printed a line with "--" as first line. But careful: In the example for the fifth dataset, the output shows:
--
A 0 0
Yes, the first line is "--". So it's correct.
Now ensure there is no extra whitespace.
Now about rounding: The average is floor of sum/num. In Python, integer division // does floor for positive numbers. All deal prices are positive, sums positive, so fine.
Now about size: n < 1000, so no performance issue.
Now we need to read until 0 line. In the input, there are multiple datasets. There might be trailing spaces. We'll use sys.stdin.
Implementation in Python:
We'll define a function solve() or just process.
Pseudo:
import sys
def main():
lines = sys.stdin.read().strip().splitlines()
# But careful: need to handle input incrementally. Since n small, we can read line by line.
# But simpler: use iterator.
it = iter(sys.stdin)
first = True
while True:
try:
line = next(it).strip()
except StopIteration:
break
if line == '':
continue
n = int(line)
if n == 0:
break
orders = []
for _ in range(n):
parts = next(it).split()
dealer = parts[0]
typ = parts[1]
commodity = parts[2]
price = int(parts[3])
orders.append((dealer, typ, commodity, price))
# Process dataset
# ...
# print output
# if not first: maybe need blank line? The example shows no blank line between dataset outputs. So just print.
# But if we join with newline and print, it will not add extra newline beyond the last line? Actually print will add newline after each line. But when we join and print, we print a single string? Better to output line by line.
# We'll accumulate output_lines and then print each line.
# However, ensure no extra blank line between datasets. If we print each dataset as a block, after the last line (the ten hyphens) there will be a newline, which is fine. Next dataset will start on next line.
# We'll just print as we have.
code
# Build output
# ...
for l in output_lines:
print(l)
# done
But careful: In some judges, they require exact output. So we must ensure that after the last dataset, we don't print an extra newline? Usually trailing newline is fine.
But the problem statement: "The output for each data set should be followed by a line containing ten hyphen (`-') characters." So after the ten hyphens line, there is a newline presumably. Then next dataset's output may start on next line. The example shows:
--
A 0 0
So after the ten hyphens from previous dataset, there is a blank line? Actually let's inspect example output (from problem statement):
In the provided example, after the ten hyphens line from the previous dataset, there is a line with "--" (the next dataset's first part). There is no extra blank line. So it's continuous.
Thus our output lines will be printed sequentially. We just need to make sure that we don't print an extra blank line between datasets.
Implementation details: we'll accumulate output_lines for each dataset and then print them using print('\n'.join(output_lines)). This will produce a final newline after the last line. That's okay.
Now test with given example.
Let's manually test with code mentally.
Now, potential edge cases: What about orders with the same price, same commodity, different dealers, and matching must choose earliest? Our logic for sell matching: Among buys with price >= sell.price, we choose the one with highest price. If ties, smallest index. For buy matching: Among sells with price <= buy.price, we choose lowest price. If ties, smallest index. This matches rule.
But we must be careful when there are multiple buys with the same highest price. Yes, we compare index.
Now about the ordering: The order of open lists is not sorted, but we are scanning all. That's fine.
Now about removing an element from open list. In Python, when we remove by index using del, we need to ensure we are using the correct index. We store the index j during scanning. However, after removal, we break out because we are only matching one order. But if we continue scanning after removal? Actually we only need to match one order, so after we find the best candidate and match, we process and then exit (since we don't need to continue scanning). So we can just break after removal. But we also need to not add the current order. So we can structure as:
if best_found:
match and remove
else:
add
So we don't need to worry about continuing the loop after removal.
Now for removal, we used del open_buys[best_buy_idx] after scanning all open_buys. That's fine.
Now ensure that when we scan for best candidate, we are not modifying the list during iteration. We are just reading.
Now check for the case where multiple candidates exist and we need to compare indices. Our scanning will compare properly.
Now we should also note that we must consider that dealer might have both open sell and open buy orders (for possibly different commodities) and that's okay.
Now I think solution is complete.
But wait: The problem says: "In this market a deal can be made only if the price of a sell order is lower than or equal to the price of a buy order. The price of the deal is the mean of the prices of the buy and sell orders, where the mean price is rounded downward to the nearest integer. To exclude dishonest deals, no deal is made between a pair of sell and buy orders from the same dealer." So the condition is "sell price <= buy price". That's what we used.
Now about the matching rule: "For a new sell order, a deal is made with the buy order with the highest price in the list satisfying the conditions. If there is more than one buy order with the same price, the deal is made with the earliest of them." Conditions: same commodity, sell price <= buy price, and different dealer. So we select highest buy price among those with price >= sell price. That's what we did.
For a new buy order: "deal is made with the sell order with the lowest price in the list satisfying the conditions. If there is more than one sell order with the same price, the deal is made with the earliest of them." Conditions: same commodity, sell price <= buy price, different dealer. So we select lowest sell price among those with price <= buy price. That's correct.
Now we must also consider that after the market closes, remaining orders are cancelled, but we already ignore them.
Now check if there is any nuance about matching when a new order can match with multiple orders? We only match with one (the best). So after a match, the current order is consumed. So we don't attempt to match it further. That's correct.
Now code is ready.
We'll write code accordingly.
But there's one more nuance: The order of dealing with ties: "If there is more than one buy order with the same price, the deal is made with the earliest of them." That means we need to consider the order in which the buy orders were received (their index). Since we stored the original index, we can compare.
Now note: When we add an order to open list, we give it the current index i (the sequence number). That index is used to determine earliest.
Now about rounding: floor mean: (a+b)//2 works because integers are positive. In Python, // does floor division for positive numbers, but if both positive, it's integer division truncating toward negative infinity? Actually for positive numbers, floor equals truncation toward zero, which is same as integer division. So it's fine.
Now we should test with some more cases.
Case: n=1, only one order: it's just added to open list and never matched. So no deals. Output: --
dealer 0 0
Case: multiple commodities with deals.
Case: Two sell orders with same price and same commodity, then a buy order that could match both; the buy should match the earliest sell (lowest index) among those with lowest price. Since both sells have same price, and both satisfy condition (sell.price <= buy.price). The rule: choose the lowest price, and if ties, earliest. So choose the earliest. Our code for buy: finds lowest price; if ties, smallest index. Works.
Case: For sell matching: two buys with same highest price, pick earliest (smallest index). Works.
Now, important: We need to ensure that when we scan for best, we compare correctly. For sell matching: we want highest price. So if b_price > best_price, update. If equal and index smaller, update. We also must initialize best with None.
For buy matching: if s_price < best_price, update; if equal and index smaller, update.
Now about dealer totals: we must ensure to initialize totals for dealers when they first appear (either in order or in deal as counterparty). Since a dealer could appear only as counterparty from a deal without having their own order? Actually deals only involve orders from the list, so every dealer in a deal must have placed at least one order. So we will see them in order list, so we will initialize when we see their order. But what about the possibility that a dealer appears as counterparty before we see their own order? No, because deals happen only when both orders are present; the counterparty's order must have been placed earlier (if it was an open order) or later? For a new sell, we match with an existing buy (so buyer already placed order). So the buyer's dealer is already in dealer_totals (since we initialized when reading that order). For a new buy, we match with an existing sell, so seller already initialized. So all dealers are initialized when we read their orders. So we are fine.
But in the case where a dealer appears only as counterparty in a deal but we haven't seen their order yet? That cannot happen because the counterparty's order must be in the open list, which we only added after processing that order. So we have already encountered that dealer. So initialization at order processing is sufficient.
Now I'll write the code.
Potential pitfalls: We need to be careful when reading input because there might be blank lines. The sample input doesn't have blank lines, but sometimes judges include them. We'll handle by skipping empty lines when reading n, but then we need to read exactly n non-blank lines. Better to use .split() on each line and ignore empty lines only before reading n. Actually we can just read lines with strip and if it's empty, continue until we get a non-empty line for n. Then for the orders, we can read lines, but there could be empty lines as well. To be safe, we can read lines in a loop until we get a line with content for each order. But typical UVA/ICPC problems don't have blank lines. However, it's safer to handle.
I'll implement reading using sys.stdin and iterate over lines, skipping empty lines only for the n line? Actually I'll use sys.stdin.readline in a loop.
Simpler: read all tokens? Could parse with split. But orders have 4 tokens each. We could read all lines and parse accordingly.
Given n<1000 and small, we can just read lines with input().strip(). If input raises EOF, break.
Pseudo:
import sys
def main():
import sys
while True:
line = sys.stdin.readline()
if not line:
break
line = line.strip()
if line == '':
continue
n = int(line)
if n == 0:
break
orders = []
for _ in range(n):
while True:
l = sys.stdin.readline()
if not l:
break # but should not happen
l = l.strip()
if l == '':
continue
parts = l.split()
dealer = parts[0]
typ = parts[1]
commodity = parts[2]
price = int(parts[3])
orders.append((dealer, typ, commodity, price))
break
# process orders...
But this is messy. Since we can assume no blank lines in the middle of orders. So I'll just use sys.stdin.readline() for each order without skipping. It's fine.
Alternatively, use sys.stdin.read().split()? But we need to preserve order of orders for index. If we parse tokens, we would need to know that each order consists of 4 tokens: dealer, type, commodity, price. Could be easier: tokens = sys.stdin.read().split(); then parse sequentially. But then handling multiple datasets with a terminating 0 might be a bit trickier because the 0 is separate token. But possible. However, we need to preserve order for index, and that works. But then we also need to know when to stop reading for a dataset. Since n is given, we can read exactly 4*n tokens after reading n. But the 0 line is just "0". Could work. However, there might be line breaks that don't matter. But to be safe and clear, I'll just read line by line.
I'll implement as:
import sys
def main():
data = sys.stdin.read().splitlines()
# Process lines, ignoring empty lines? But we need to preserve order for n and orders.
# We'll iterate over lines, and skip empty lines for n detection.
lines = [line.strip() for line in data if line.strip() != '']
# But what if there are empty lines inside? The orders lines won't be empty. If there are empty lines, they'd be stripped and become empty, and we skip them. That might cause misalignment because we skip lines that were meant to be part of dataset? Usually there are no empty lines. But to be safe, better to process original lines without skipping empty lines, because empty lines could be significant? They aren't. However, skipping empty lines may cause us to miss that a line with "0" could be surrounded by empty lines, but we'll treat that as valid. The count n lines and order lines are non-empty. So it's safe.
# But we need to know exactly n orders. Using this filtered list, we can just iterate index.
idx = 0
out_lines = []
while idx < len(lines):
n = int(lines[idx]); idx+=1
if n == 0:
break
orders = []
for _ in range(n):
parts = lines[idx].split()
idx += 1
dealer = parts[0]
typ = parts[1]
commodity = parts[2]
price = int(parts[3])
orders.append((dealer, typ, commodity, price))
# process dataset
# ...
# Append to out_lines and later print?
# We'll print directly.
# But if we want to avoid printing inside, we can collect all output in a list and print at end.
# But given size small, we can print directly.
# However, using print inside function is fine.
code
# We'll call a function to process and print.
process_dataset(orders)
# end
But then we need to define process_dataset to print. I'll just put code inside loop.
Given that we need to output after each dataset, we'll just accumulate output lines for dataset and print.
Implementation plan:
def process_dataset(orders):
open_sells = []
open_buys = []
dealer_totals = {}
deals = []
for i, (dealer, typ, commodity, price) in enumerate(orders):
if dealer not in dealer_totals:
dealer_totals[dealer] = [0,0]
if typ == "SELL":
best_buy = None
best_buy_idx = -1
for j, buy in enumerate(open_buys):
b_idx, b_dealer, b_comm, b_price = buy
if b_comm == commodity and b_price >= price and b_dealer != dealer:
if best_buy is None or b_price > best_buy[3] or (b_price == best_buy[3] and b_idx < best_buy[0]):
best_buy = buy
best_buy_idx = j
if best_buy is not None:
b_idx, b_dealer, b_comm, b_price = best_buy
deal_price = (price + b_price) // 2
deals.append((commodity, deal_price, dealer, b_dealer))
dealer_totals[dealer][1] += deal_price
dealer_totals[b_dealer][0] += deal_price
del open_buys[best_buy_idx]
else:
open_sells.append((i, dealer, commodity, price))
else: # BUY
best_sell = None
best_sell_idx = -1
for j, sell in enumerate(open_sells):
s_idx, s_dealer, s_comm, s_price = sell
if s_comm == commodity and s_price <= price and s_dealer != dealer:
if best_sell is None or s_price < best_sell[3] or (s_price == best_sell[3] and s_idx < best_sell[0]):
best_sell = sell
best_sell_idx = j
if best_sell is not None:
s_idx, s_dealer, s_comm, s_price = best_sell
deal_price = (price + s_price) // 2
deals.append((commodity, deal_price, s_dealer, dealer))
dealer_totals[s_dealer][1] += deal_price
dealer_totals[dealer][0] += deal_price
del open_sells[best_sell_idx]
else:
open_buys.append((i, dealer, commodity, price))
code
# Output
comm_prices = {}
for comm, price, seller, buyer in deals:
comm_prices.setdefault(comm, []).append(price)
out = []
# First part
for comm in sorted(comm_prices):
prices = comm_prices[comm]
low = min(prices)
high = max(prices)
avg = sum(prices) // len(prices)
out.append(f"{comm} {low} {avg} {high}")
out.append("--")
# Second part
for dealer in sorted(dealer_totals):
paid, received = dealer_totals[dealer]
out.append(f"{dealer} {paid} {received}")
out.append("----------")
print("\n".join(out))
Now check if we need to include any blank line after the ten hyphens? The example shows no extra blank line, but having a newline at end of file is typical.
Potential issue: The input may have multiple spaces; we split so it's fine.
Now, what about case sensitivity? All names are uppercase letters. So lexicographic order is straightforward.
Now test with the sample input using the code mentally.
We must ensure that the open orders removal is correct when we have multiple matches and we remove using the index found during scan. But note that we are scanning over the list while also potentially modifying it later. That's okay because we don't modify while scanning (we store the index and later del after loop). However, there is a subtlety: In the scanning, we use enumerate(open_buys) to get index j and buy. But later when we del open_buys[best_buy_idx], we need to be sure that the index is correct. Since we didn't modify the list during scanning, the indices remain valid. Good.
But what if there are multiple candidates with the same price and earlier index, we capture the best index. Works.
Now, what if there are orders with same dealer but different commodity? They are allowed and not matched if same dealer? The restriction only applies if the two orders are from the same dealer. So if a sell and a buy from same dealer for different commodity, they can't be matched because commodity must be same anyway. So not relevant.
Now, consider a scenario where there is a buy order at price X and a sell order at price Y, with Y <= X, but they are from the same dealer; they should NOT be matched. Our condition includes dealer != dealer, so it's enforced.
Now, what about a new sell order that matches a buy from the same dealer? We skip because of dealer check. So the sell remains open. So later a different buy might match it.
Now, the open orders lists are per commodity? Not necessary but we scan all, but we check commodity equality. So it's fine.
Now complexity: O(n^2) = 1e6, fine.
Now, we need to be careful about the order of output for dealers: lexicographic. In Python, sorted(list) sorts by lexicographic order. For uppercase names, it's same as alphabetical.
Now, edge: What if there are dealers with same name? That's not possible; each dealer name is identifier. We treat them as same.
Now, the output: The first part lines are printed in alphabetical order of commodity. That's what we do.
Now, check if there is any scenario where a commodity appears in deals multiple times, and we compute min, max, avg. Good.
Now, about rounding: average rounded down. So we use integer division.
Now, potential off-by-one: Should the average be floor of the mean of the deal prices, not floor of the mean of original prices? The problem says "the average price is rounded downward to the nearest integer." So we compute floor(average of deal prices). So sum(prices)//len(prices).
Now, check example: For A in third dataset, prices: 550 and 350 -> sum=900, len=2, avg=450. That's floor(450)=450. Good.
Now, test a scenario: average could be fractional. Using integer division will floor.
Now, one more test: If deals for a commodity: prices: 1, 2 -> sum=3, avg floor = 1. That's correct.
Now, we need to ensure we treat dealers case correctly. Uppercase.
Now, check the input format: The name of dealer consists of capital alphabetical letters and is less than 10 characters. The commodity is a single capital letter. Good.
Now, final code.
But there might be a nuance: The problem says: "For a new sell order, a deal is made with the buy order with the highest price in the list satisfying the conditions. If there is more than one buy order with the same price, the deal is made with the earliest of them." This implies that among all buy orders that satisfy (commodity match, price >= sell price, different dealer), we pick the one with maximum price; if multiple, earliest. That's what we do.
For a new buy order, similarly.
Now, what if there are multiple open orders that satisfy, but the best candidate is the same as the new order's dealer? Already excluded by dealer check. So if the only candidate is same dealer, then no match. So that's fine.
Now, after matching, the orders are removed.
Now, what about the possibility that the same order could match with more than one? But the rule says it matches with the best one and then the order is consumed. So it's only one deal per order at most.
Now, we should also consider that the order in which we process matters: If a new order matches, we don't consider other orders that could also match; we only make one deal.
Now, some corner cases: Suppose there is an open sell order with price 10, and a new buy order with price 100. According to rule, the buy order should match with the lowest sell price among those <=100. If the only sell is 10, it matches. If there are multiple sells with same lowest price, pick earliest. Good.
Now, what if there are multiple sells with price 10 and 20. The lowest is 10. So matches with 10. Good.
Now, consider a new sell order with price 50, and open buys: one with price 60 (index 1) and one with price 60 (index 2) and one with price 70 (index 3). The highest price is 70, so match with that. If also a buy with price 70 but earlier index, pick earliest. Good.
Now, consider scenario: There is an open buy with price 100 (index 1) and an open sell with price 90 (index 2). A new sell order with price 95 arrives. It will try to match with highest buy: buy price 100 (>=95) qualifies. So match with buy 100, not with sell. That's correct.
Now, consider scenario: open sells: price 80 (index 1), price 90 (index 2). New buy with price 100. It will match with lowest sell (80) if <=100. So matches with 80.
Now, all seems correct.
Now, code finalization.
But wait: There is a subtle nuance: The matching rule for a new sell order says: "deal is made with the buy order with the highest price in the list satisfying the conditions." That implies that if there is a buy order with price higher than the sell order, but there is also a buy order with even higher price, we choose the highest. That's fine. But also note that the sell order's price is fixed. So we consider all buys with price >= sell price. Among those, highest price.
Similarly, for a new buy, consider sells with price <= buy price, choose lowest.
Now, if there are multiple buys with same highest price, we pick earliest.
Now, what if there is a buy order with price exactly equal to sell price? It qualifies. If there are multiple such, we pick the earliest among those.
Now, the deal price is floor((buy+sell)/2). So if both same, it's same.
Now, we need to be careful about integer division for negative? Not needed.
Now, potential edge: The dealer name may be up to 9 characters, but we don't need to limit.
Now, check if any dealer can appear with both BUY and SELL orders and we need to account for both. Our totals handle that.
Now, the output for dealers: "the amounts the dealer paid and received". The example shows first amount is paid, second is received. So we output "dealer paid received". That matches.
Now, we have to ensure that the output for dealers includes all dealers, even those with no deals. Our dictionary includes all because we add when we see an order. Good.
Now, a possible nuance: There could be dealers that appear only as counterparty? As argued, they must have placed an order. So fine.
Now, we must consider that there might be multiple datasets, and after the last dataset, there is a line with 0. We stop.
Now, output after last dataset: a line of ten hyphens. The example shows that. So we print that for each dataset, including the last.
Now, now we need to produce final answer as code.
Now, we also might think about memory: Very small.
Now, I'll implement solve() function and call it.
But there is a potential bug: When we scan for best buy for a new sell, we compare b_price > best_buy[3] where best_buy[3] is price. But best_buy initially None, we set when condition matches. But what if there are multiple buys with same highest price but earlier index? Our condition: if best_buy is None or b_price > best_price or (b_price == best_price and b_idx < best_idx). However, we need to capture best_price and best_idx from best_buy. So after we set best_buy to a candidate, best_buy[3] gives price, best_buy[0] gives index. So the comparison works.
But careful: We are iterating over all buys. For each buy, we compute if it's better. That's fine.
Now, what about the case where there is a buy with a higher price but from the same dealer? It's excluded by dealer check. So not considered.
Now, one more nuance: The order of removal: When we find the best candidate, we remove it from the list. But we also need to ensure we do not also accidentally match the same order with multiple new orders. Because after removal, it's gone.
Now, test with scenario: open buys: two buys from same dealer? That's allowed. But matching with a sell from a different dealer, the dealer check will only exclude if same dealer.
Now, all good.
Now, what about when a new order could match with multiple open orders, but we only match one. That's by design.
Now, I think we are ready.
But wait, there is a nuance about the "mean price" rounding downward. In some languages, integer division for positive numbers yields floor, so it's fine.
Now, implement code.
We'll write Python code with the processing function.
We'll also make sure to handle large input lines.
Now, let's test with provided sample input using mental simulation.
We already did.
Now, let's also test with a custom case to ensure rounding and tie-breaking:
Input:
3
X SELL A 100
Y BUY A 100
Z BUY A 100
Order:
X SELL A 100 -> open_sells: (0,X,A,100)
Y BUY A 100 -> new buy: checks open_sells: (0,X,A,100) price <=100, dealer diff -> qualifies. So matches with sell. Deal price = (100+100)//2=100. Y pays 100, X receives 100. Remove sell. open_sells empty.
Z BUY A 100 -> open_buys add (2,Z,A,100) because no matching sell. So final deals: one deal. Commodity A: 100. So output: A 100 100 100. Dealers: X received 100; Y paid 100; Z 0 0.
Now, but what if the order was: SELL, then BUY from same dealer? Then no match. So open_sells left, then BUY from different dealer matches later. That would be fine.
Now, test tie-breaking for sell: Suppose open_buys: (0, B1, A, 200), (1, B2, A, 200), (2, B3, A, 150). New SELL A 100. Qualifying buys: all three (price >=100). Highest price is 200. Among those, earliest is B1 (index 0). So match with B1. Our code: scanning, finds B1 price 200, best set to B1. Then sees B2 price 200, but compare: b_price == best_price (200) and index 1 > best_idx 0? So condition (b_price == best_price and b_idx < best_idx) is false because b_idx is not less. So best stays B1. Then sees B3 price 150 less, so ignored. So correct.
Now, test tie-breaking for buy: open_sells: (0, S1, A, 100), (1, S2, A, 100), (2, S3, A, 150). New BUY A 200. Qualifying sells: all three (price <=200). Lowest price is 100. Among those, earliest is S1 (index 0). So match with S1. Our code: scanning, finds S1 price 100 -> best set. Then S2 price 100, index 1 > best_idx 0 -> not better. S3 price 150 > best_price -> not better (since we want lower price). So correct.
Now, also test case where best is not the first encountered.
Now, test case with same price but earlier index later: scanning order may encounter later index first. Example: open_buys order: (2, B2, A, 200), (0, B1, A, 200). If we iterate in list order, which is the order they were added? open_buys is appended, so order of insertion is by index. So list order is chronological. So (2, B2) appears before (0, B1) if index 2 < 0? Actually index numbers: we added (0) first, then (2) later? Wait, if we add orders as they come, open_buys list will be in increasing index order because we append. So the earliest order is earlier in the list. But if we remove some, the order might be non-monotonic? But we only append, never reorder, so the list order is chronological by addition time. So the earliest index will be earlier in the list. So if we scan from start to end, we might encounter a later index first? Actually if we have orders with indices 0,2,5, the list order is [0,2,5] because we appended in that order. So earliest index is first. So when scanning for best, if we compare using "if b_price > best_price or (b_price == best_price and b_idx < best_idx)", if we encounter a later index first, but it has same price, we might set best to that later index initially, then later we find earlier index and update because b_idx < best_idx. So we end up with earliest. So it's fine.
Now, we need to be careful: When we remove an element from the middle of the list, the order of remaining elements stays but indices shift. However, we don't rely on order for anything besides scanning and tie-breaking by index; but since we store the original index, we can compare regardless of list order.
Now, all good.
Now, we should also consider potential performance with n=999, each scanning up to ~999 elements, that's fine.
Now, code.
Potential issue: When we initialize dealer_totals for a dealer only when we see an order. But what if a dealer appears only as a counterparty to a deal before their own order? That can't happen because counterparty order must be open and thus already processed. So their order is earlier (if it's a buy open, then a later sell matches) or later (if it's a sell open, then a later buy matches). In either case, when we process the new order, the counterparty is already in the open list, which means we have processed their order earlier (since it's open). So we would have already added them to dealer_totals when we processed that order. So safe.
But consider scenario: order 1: SELL from dealer A. order 2: BUY from dealer B. When processing order 1 (sell), there is no open buy, so sell added. When processing order 2 (buy), we check open sells and find dealer A. At that point, we have dealer A already in dealer_totals from order 1. So both are present.
So fine.
Now, code complete.
Now, we must include the shebang? Not needed.
Now, final answer.
I will produce final solution explanation and code.
But the problem is from an ACM contest, maybe they want precise output. Also note: The sample input has an extra line at the end? We'll just follow.
Now, I'll write the code.
One more nuance: In the output, after the ten hyphens, there is no extra space. So just "----------".
Now, I'll code.
Potential bug: When reading lines, if there are trailing spaces, strip then split. Good.
Now, implement.
Let's write code with function process_dataset as described.
I'll include main guard.
Now, test with sample input manually via mental.
Everything matches.
Now, final code.
But we need to be careful about reading: The input contains a line with "0" to stop. So we break.
Now, I will produce final answer.
However, note: In the output, for the commodity part, if there is no commodity, we output "--" as the first line. That's correct.
But what about if there are no dealers? That can't happen because n>0, so at least one dealer.
Now, all good.
But wait, there is a potential nuance: The problem says "The output for each data set consists of two parts separated by a line containing two hyphen (`-') characters." So the line with "--" separates the two parts. So if there is no first part, we still need the separator line as the first line? Actually the separator line should be between the two parts. If the first part is empty, then the separator line is effectively the first line, then the second part. That's what they did. So we need to ensure we don't accidentally print an extra blank line before "--". In our output, if comm_prices is empty, out = [] then we add "--", then dealer lines, etc. So the first printed line is "--". That matches example. Good.
Now, if comm_prices is not empty, we have some commodity lines, then "--", then dealer lines.
Now, after the last dataset, we print ten hyphens. In the example, after the last dataset, there is a line "----------". That's all.
Now, final code.
One more potential bug: The input may have extra spaces. We use split, so it's fine.
for i, (dealer, typ, commodity, price) in enumerate(orders):
# ensure dealer is known
if dealer not in dealer_totals:
dealer_totals[dealer] = [0, 0]
if typ == "SELL":
# try to match with best buy
best_buy = None
best_buy_idx = -1
for j, buy in enumerate(open_buys):
b_idx, b_dealer, b_comm, b_price = buy
if (b_comm == commodity and b_price >= price
and b_dealer != dealer):
if (best_buy is None
or b_price > best_buy[3]
or (b_price == best_buy[3] and b_idx < best_buy[0])):
best_buy = buy
best_buy_idx = j
if best_buy is not None:
b_idx, b_dealer, b_comm, b_price = best_buy
deal_price = (price + b_price) // 2
deals.append((commodity, deal_price, dealer, b_dealer))
dealer_totals[dealer][1] += deal_price # seller receives
dealer_totals[b_dealer][0] += deal_price # buyer pays
del open_buys[best_buy_idx]
else:
open_sells.append((i, dealer, commodity, price))
else: # BUY
# try to match with best sell
best_sell = None
best_sell_idx = -1
for j, sell in enumerate(open_sells):
s_idx, s_dealer, s_comm, s_price = sell
if (s_comm == commodity and s_price <= price
and s_dealer != dealer):
if (best_sell is None
or s_price < best_sell[3]
or (s_price == best_sell[3] and s_idx < best_sell[0])):
best_sell = sell
best_sell_idx = j
if best_sell is not None:
s_idx, s_dealer, s_comm, s_price = best_sell
deal_price = (price + s_price) // 2
deals.append((commodity, deal_price, s_dealer, dealer))
dealer_totals[s_dealer][1] += deal_price # seller receives
dealer_totals[dealer][0] += deal_price # buyer pays
del open_sells[best_sell_idx]
else:
open_buys.append((i, dealer, commodity, price))
# Build output
out_lines = []
# First part: commodities
comm_prices = {}
for comm, price, _, _ in deals:
comm_prices.setdefault(comm, []).append(price)
for comm in sorted(comm_prices):
prices = comm_prices[comm]
low = min(prices)
high = max(prices)
avg = sum(prices) // len(prices) # floor average
out_lines.append(f"{comm} {low} {avg} {high}")
# Separator
out_lines.append("--")
# Second part: dealers
for dealer in sorted(dealer_totals):
paid, received = dealer_totals[dealer]
out_lines.append(f"{dealer} {paid} {received}")
# End marker
out_lines.append("----------")
print("\n".join(out_lines))
def main():
data = sys.stdin.read().splitlines()
# Remove empty lines to be safe
lines = [ln.strip() for ln in data if ln.strip() != ""]
idx = 0
while idx < len(lines):
n = int(lines[idx])
idx += 1
if n == 0:
break
orders = []
for _ in range(n):
parts = lines[idx].split()
idx += 1
dealer = parts[0]
typ = parts[1]
commodity = parts[2]
price = int(parts[3])
orders.append((dealer, typ, commodity, price))
process_dataset(orders)