USACO 2018 Open: Milking Order and Topological Sort


USACO 2018 US Open Contest, Gold

Problem 2. Milking Order


We need to find the biggest number X such that the first X observations are satisfied.
Notice that this is perfect to do a binary search on: the invariant is that if the first X observations are satisfied, all observations X-1 will be satisfied; if the first X are insatisfied, all observations X+1 will not be satisfied.
So how do we check if all observations to X are satisfied?
Let us assemble a graph, in which each observation O_1, O_2, O_3, ... O_i, ... O_l(o) is represented as an edge between O_i and O_i+1 for all i. These observations are satisfiable if and only if this graph has a topological sorting.
Lexicographic topological sorting on a graph can be done in O(E + V log_2 V) time (log_2 V because of priority_queue to extract lowest element). So, our total time complexity will be O((E + NlogN) logM). Here, E=200K (the sum of the M_i), N=100K, and M=50K, so it's fast enough.
LTS can be easily implemented with a priority queue:

  • Assemble the graph. Whilst adding edges, keep track of how many directed edges point towards a node.
  • Add every node that isn't pointed to into the priority queue.
  • (BFS-ish part) While the priority queue is not empty, pop the lowest element.
  • Add this element to the LTS sequence.
  • Remove all edges extending from that element, and update the in-edge count accordingly.
  • If there are any new nodes with an in-edge count of 0, push it into the queue.
  • Continue until the sequence is empty.
  • If any nodes were not visited, LTS is impossible.
  • Else the LTS is in the sequence.

Comments

Popular posts from this blog

USACO Training "subset": Subset Sums

USACO 2018 Open: Talent Show

OpenJudge 1768: Kadane's Algorithm on 2D Arrays