Slalom

Time limit1sMemory limit128 MB

Summary
Given a start point and a sequence of horizontal gates at decreasing heights, find the minimum-length path from the start that passes through each gate segment in order.
Level

Medium6 of 10

Topics
Geometry, Greedy, Binary search
Solved
No attempts yet

Problem

Although snowfall is scarce in Madrid, interest in winter sports is growing there, especially in skiing, and many people spend weekends or even whole weeks improving their skills in the mountains. This problem deals with just one of the alpine skiing disciplines: the slalom. A course is built by laying out a series of gates, each formed by two poles. The skier must pass between the two poles of every gate, and the winner is the one who completes the course in the least time without missing any gate.

You have only recently started to learn to ski, but you have already set yourself the goal of taking part in the Winter Olympic Games of 2018, for which Madrid is expected to present a candidature. As part of your theoretical training, you must write a program that, given a starting point and a series of gates, computes the minimum length of a path that starts at the given point and passes through each gate in turn until it reaches the last one, which is the finish line. You may assume that the gates are horizontal and are ordered from highest to lowest, so that you must pass through them in that order. You consider yourself an accomplished skier who can make any series of turns, no matter how difficult, so your only concern is minimizing the total length of the path.

Input

The input contains several test cases. The first line of each case gives the number of gates nn (1≤n≤10001 \le n \le 1000). The next line contains two floating-point numbers, the Cartesian coordinates xx and yy of the starting position, in that order. Then come nn lines with three floating-point numbers each, yy x1x_1 x2x_2, meaning that the corresponding gate is the horizontal segment from (x1,y)(x_1, y) to (x2,y)(x_2, y). You may assume that x1<x2x_1 < x_2. The values of yy are strictly decreasing and are always smaller than the yy of the starting position. The last gate is the finish line. All coordinates are between −500000-500000 and 500000500000, inclusive. A value of 00 for nn means the end of the input. A blank line follows each case.

Output

For each test case, print on its own line the minimum length of the path needed to reach the finish line, rounded to exactly 66 digits after the decimal point. The test data guarantee that the exact answer never lies on a halfway point of the sixth decimal, so this rounding is unambiguous.

Examples1

  1. Example 1

    Input
    2
    0 2
    1 1 2
    0 0.5 3
    
    3
    0 4
    3 1 2
    2 -1 0
    1 1 2
    
    0
    
    Expected output
    2.414214
    4.242641