eolymp
bolt
Попробуйте наш новый интерфейс для отправки задач
Задачи

Iceberg Orders

Iceberg Orders

Вы работаете на бирже Метагония. Недавно торговцы в Метагонии услышали о заявках айсберга, торгуемых на Лондонской фондовой бирже, и попросили вашего работодателя добавить такую функциональность. Фондовая биржа - это финансовый институт, который получает заказы и генерирует сделки.

Заявка айсберга - это пятека целых чисел (ID, T, P, V, TV). Каждая заявка имеет идентификатор ID (уникальный для всех заявок), тип T (равный либо BUY = 1 или SELL = 2), цену P, общий оставшийся объем V и видимый объем TV . Для каждой заявки дополнительно отслеживается ее текущий объем CV и приоритет PR. Существует также глобальный счетчик приоритетов обмена GP. Заявка включается в набор заявок биржи.

Торги, которые генерируются на бирже, представляют собой четыре целых числа (BUY-ID, SELL-ID, P, V). Каждая сделка содержит BUY-ID и SELL-ID - идентификаторы соответствия ПОКУПАТЬ и ПРОДАВАТЬ заказы, торговую цену P и объем торгов V.

Когда заявка выставляется на торги, она сопоставляется с заявками, находящимися в настоящее время в реестре заявок. Это происходит следующим образом. Пусть получен заказ a, у которого Ta = SELL. Среди всех заявок, выставленных на торги, мы ищем заявку b такую что Tb = BUY и PbPa. Мы выбираем такую заявку b, которая имеет наибольшую цену, а если таких несколько - то имеющую наименьший приоритет. Если такая заявка b существует, то a генерирует торговую сделку t у которой BUY-IDt = IDb и SELL-IDt = IDa по цене Pt = Pb объемом Vt = min(Va,CVb). Значения Va, Vb и CVb уменьшаются на объем сделки. Если после этого Vb = 0, то заявка b удаляется из реестра заявок. Если CVb = 0 (но Vb > 0), то устанавливаем текущий объем заявки b равным CVb = min(Vb, TVb), устанавливаем PRb = GP, и увеличиваем GP. Продолжаем операции выбора b и генерирования торгов пока не станет либо Va = 0, либо не станет больше таких заявок b в реестре, удовлетворяющих условию возможности торгов. In the latter case, we add order a to the order book with CVa = min(Va, TVa) and PRa = GP, and then increment GP. When the process of matching the order a is finished with several trades between the same pair of orders a and b (and there can be lots of them!), they are all united into a single trade with the volume equal to the sum of individual trade volumes.

If Ta = BUY we are looking for an order b with Tb = SELL and PbPa and select such an order b with the smallest price and the smallest priority among those. The rest of the matching process is as described above, with trades having BUY-IDt = IDa, SELL-IDt = IDb, Pt = Pb, and Vt = min(Va,CVb).

Initially the order book is empty. You are presented with several orders that are received by the exchange one by one. You need to print generated trades and the order book state after all orders are processed.

Hint: The priority and GP are introduced in the problem statement only for the purpose of a formal description of the algorithm. The actual implementation does not have to keep track of priority. Typically, an exchange simply keeps a priority-ordered list of orders of each type at each price in its order book.

Входные данные

Первая строка содержит количество заявок n (1n50000). Каждая из следующих n строк представляет заявку. Каждая заявка задается пятеркой ID T P V TV, где 1ID1000000, T = 1 для BUY и T = 2 для SELL, 1P100000 и 1TVV109.

Выходные данные

For each order print all trades generated by processing this order, in ascending order of pairs (BUY-ID, SELL-ID), each trade on its own line. Each trade shall be printed as a space-separated quadruple of integers BUY-ID SELL-ID P V. It is guaranteed that the total number of trades would not exceed 100000. Print a blank line after all trades, followed by the order book. Each order that is still on the book shall be printed as a space-separated sextuple ID T P V TV CV, sorted first by P and then by PR.

Пояснение

В примере первые четыре заявки имеют T = BUY. Предполагая что в начале торгов GP равнялось 1, после получения этих заявок реестр выглядит следующим образом, упорядоченный по правилам соответствия из условия задачи для Tb = BUY (сначала по убыванию цены, затем по возрастанию приоритета):

prb7569.gif

Пятая заявка (IDa = 4321) имеет Ta = SELL, Pa = 99 и Va = 125 and is eligible for match with all of the above four orders given in the above table. First, it matches twice with the order 1111 with the highest price of 101 for a total trade volume of 30, removes it from the order book, bumps GP to 6 in the process, and decreases Va to 95. Then, there are three other orders at price 100. One matching pass through them produces three trades for a total volume of 85 (volume 20 with order 42, volume 50 with order 239, removes it from the book, volume 15 with order 1234), bumps GP to 8, and decreases Va to 10. The remaining orders in the book are shown below:

prb7569_1.gif

One last match with the order 42 produces a trade with a volume of 10 (for a total volume of 30 for matches with order 42) and the order 4321 is done (Va = 0). Four corresponding total trades for order 4321 are printed in the sample output. The remaining order book is:

prb7569_2.gif

The sixth BUY order (with ID = 5678) is added to the order book (GP becomes 9):

prb7569_3.gif

The last, seventh order (with ID = 8765), can be matched only with the order 5678 due to price condition, generates a trade with volume of 30, order 5678 is removed from the order book, while order 8765 is added. Now the order book has both BUY and SELL orders:

prb7569_4.gif

Лимит времени 1 секунда
Лимит использования памяти 128 MiB
Входные данные #1
7
42 1 100 200 20
239 1 100 50 50
1111 1 101 30 15
1234 1 100 300 15
4321 2 99 125 25
5678 1 101 30 30
8765 2 101 100 20
Выходные данные #1
42 4321 100 30
239 4321 100 50
1111 4321 101 30
1234 4321 100 15
5678 8765 101 30

42 1 100 170 20 10
1234 1 100 285 15 15
8765 2 101 70 20 20
Источник 2015 ACM NEERC, Semifinals, December 6, Problem I