Editorial for Baltic OI '13 P1 - Ball Machine
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
General considerations
- Because of the queries of type "insert balls", you might think that you have to insert multiple balls at once to be quick enough. But as there can never be more than balls in the machine, and they are only removed one by one, only balls are ever added, so it is fine to insert them one by one.
- You can pre-compute for each node the smallest number inside of its subtree. This takes with one DFS.
- Now you can easily simulate the whole process always taking one step at a time. This approach takes time, where is the depth of the tree, and the maximum degree of any node. On the balanced-tree lower limit, it is and , so the total time is which is fine. But on a degenerate tree (i.e. a line), it becomes which is too slow.
Fast Insertion
- After sorting the (direct) children of each node by lowest number in their respective subtree, do another DFS to compute the post-order index of each node.
- These post-order indices are the priorities, by which nodes are getting filled by the add-queries. Therefore you can keep all empty nodes in an appropriate data structure that allows you to find the node to be filled in time. A set or priority queue will both work here.
Fast Deletion
- Let denote the parent of node . You can precompute for all and all appropriate . This will take space, and with a little DP time.
- Now you can speed up the roll-down part of a removal query to only take time.
Comments