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.

General considerations

  • Because of the queries of type "insert k 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 N balls in the machine, and they are only removed one by one, only O(Q) 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 O(N) with one DFS.
  • Now you can easily simulate the whole process always taking one step at a time. This approach takes O(QDR) time, where D is the depth of the tree, and R the maximum degree of any node. On the balanced-tree lower limit, it is D=O(logN) and R=2, so the total time is O(NlogN) which is fine. But on a degenerate tree (i.e. a line), it becomes O(N2) 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 O(logN) time. A set or priority queue will both work here.

Fast Deletion

  • Let p(x) denote the parent of node x. You can precompute p(2k)(x) for all x and all appropriate k. This will take O(NlogN) space, and with a little DP O(NlogN) time.
  • Now you can speed up the roll-down part of a removal query to only take O(logD) time.

Comments

There are no comments at the moment.