Editorial for COCI '15 Contest 2 #3 Artur


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.

Let us first notice that there is always going to be at least one stick that can be removed from the table in a manner that follows the rules of the game. In other words, a solution always exists.

The first step towards solving the task is answering the question: "Is stick B in the way of moving stick A?". We observe the projections of the corresponding line segments on the x-axis. A projection of a line segment with ending points (x_1, y_1) and (x_2, y_2) corresponds to the line segment with ending points (x_1, 0) and (x_2, 0). If the observed projections don't have points in common, then the removal of sticks A and B is mutually independent. Otherwise, let (x', 0) denote one of the mutual points of two projections. Let T_A denote the intersection of line x = x' with stick A, and T_B denote the intersection of that line with stick B. Stick B is in the way of moving stick A if T_A is located above T_B. Therefore, the answer to the given question is obtained in \mathcal O(1).

Let us imagine that each line segment corresponds to a node in a directed graph and that there is an edge from node A to node B if and only if stick B is in the way of moving stick A. Now we need to find a sequence of nodes so that it holds for each directed path between a and b that node a is located before node b in that sequence. This order of nodes is called topological sort and it is found using a slight modification of depth-first search (DFS). More precisely, after we have expanded from one node to all its neighbours, we add that node to the end of the sequence. This way, we have made sure that all line segments in the way of moving the current one are removed before we remove the current line segment.

The time complexity of this algorithm is \mathcal O(N^2) because of building the graph. The topological sort itself is as efficient as a DFS traversal of the graph.


Comments

There are no comments at the moment.