Two Mountaineers
Time limit1sMemory limit128 MB
Given a polygonal mountain profile with equal endpoints, find the minimum total elevation change for two climbers who swap endpoints while staying at equal height.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Geometry, Implementation
- Solved
- No attempts yet
Problem
Two mountaineers stand at opposite ends of a mountain range at exactly the same elevation. Each wants to walk along the range and reach the other climber's starting point, and throughout the journey the two must always stay at the same elevation. To keep their elevations equal, a climber may move either forward or backward along the range. As long as the range never drops below the starting elevation, the two climbers can always exchange starting points in this way. Given the shape of a mountain range, compute the minimum possible sum of the lengths of the two climbers' walks.
The mountain range is modeled as a polygonal chain with vertices . It is monotone in the -direction, i.e. , so it is the graph of a piecewise-linear function of .
A walk of a climber is a sequence of points on such that every consecutive part lies on . The length of a single step is measured only by the change in elevation, (horizontal movement contributes nothing), and the length of the whole walk is the sum of the lengths of its steps. Climber A starts at and climber B starts at ; since they begin at the same elevation, .


For example, in the figure above, the left climber's walk is , and the resulting sum of the two climbers' walk lengths is , which is the minimum.
Input
The first line contains the number of test cases ().
Each test case is given as follows. The first line contains an integer (), the number of vertices of the polygonal chain . Each of the next lines contains two integers and (), the coordinates of , listed in the order . The -coordinates are strictly increasing.
Climber A starts at and climber B starts at , so . In every test case the mountain range never drops below the starting elevation, and the vertex elevations are all distinct except that the two endpoints share the starting elevation ().
Output
For each test case, print a single line containing the minimum possible sum of the two climbers' walk lengths.