You are tasked with simulating an order book for a market, like a stock exchange. You will be given a series of incoming orders, which can either be bids (offers to buy) or asks (offers to sell).
Your program must process these orders, execute any possible trades, and then print the final state of the order book at the end of the day.
The matching logic is as follows:
A trade occurs when the highest bid price is greater than or equal to the lowest ask price.
When a new bid arrives, it is matched against the asks in the book, starting from the one with the lowest price.
When a new ask arrives, it is matched against the bids in the book, starting from the one with the highest price.
A trade is executed at the price of the order that was already in the book (the resting order).
If an incoming order is not fully filled after matching, the remaining quantity is added to the book.
If an order is placed at a price that already exists in the book, the quantities are aggregated.
Input Format: The first line contains an integer n, the total number of orders.
The next n lines each describe an order with three space-separated integers: a p q
a: The order type
0 for a bid
1 for an ask
p: The price of the order
q: The quantity of the order
Output Format: Print the final state of the order book.
Each line in the output should represent a price level remaining in the book and contain three space-separated values:
A P Q
A: The order type (0 for bid, 1 for ask)
P: The price level
Q: The total aggregated quantity available at that price
The output must be sorted in descending order of price P.
Medium