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.
In this problem, we are given
dots in a 2D-plane with distinct
coordinates and
coordinates. Our task is to construct a broken line starting from the origin that will cover all dots.
solution
An easy solution is to use
segments to cover each dot (for example: first set the
coordinate, then
coordinate). This solution uses
segments and receives
points.
Spiral
Let us consider the left-most, top-most, right-most and bottom-most dot. They create a bounding box which we can cover with
segments. We can remove these points and continue with a smaller problem. To connect the bounding boxes, we can just continue the line from the inner bounding box and go toward the proper direction in the outer box. This solution receives about
points, depending on the implementation.
Chain
Let us notice that we can cover a chain of points (for example with increasing
and
values) without wasting any segment. From Dilworth's theorem, we know that in the sequence of length
, there exists an increasing sequence or decreasing sequence of length
. We can find this sequence in
. Moreover, we can decompose the whole sequence into
increasing and decreasing sequences. Therefore in our problem, we can create
chains and connect them with
additional segments. This solution uses
segments and receives about
points.
solution
Let us reconsider the spiral. We waste additional segments only if the bounding box contains less than
points (for example there's a point that is both the left-most and the top-most one). We can remove these points and put them in one of two chains (one going from the top-left corner to the bottom-right corner) and one going from the top-right corner to the bottom-left one).
The algorithm is as follows:
- if a bounding box has
points in it, add them to the spiral, and remove these points,
- otherwise, find a point that lies on two sides of the bounding box, add it to the proper chain and remove it.
Then we have three objects (spiral and two chains) and we can use up to
segments to connect them to themselves and the origin. This solution gets about
points.
solution
To come up with an even better solution, we need to add some small tricks, including considering all possible orders in which we can connect these objects and directions in which we can traverse them. These optimizations lead a solution with
segments, which gets
points.
Comments