Find the shortest time for a worm to travel from the base of tree 1 to the top of tree N, where each climb, jump, and gravity rest costs one second, with a free move when standing on a tree top.
Medium7GraphShortest pathDynamic programmingImplementationNo attempts yetTime limit1sMemory limit512 MBA forest has N trees standing in a row at positions 1 through N. Tree i has height hi. The worm is at the base of tree 1, at height 0, and it wants to reach the top of tree N, at height hN.
The worm can make one of two moves.
Each move takes exactly 1 second, even when the top or the base of a tree cuts the move short.
After a move the worm must rest for 1 second, and while it rests gravity drags it down by di units on tree i. It never goes below height 0. There is one exception. If a move leaves the worm on the top of the tree it is standing on, it does not rest and moves again right away.
The trip ends the moment the worm reaches the top of tree N.
Given the number of trees and every hi, ui and di, find the shortest travel time in seconds from the base of tree 1 to the top of tree N.
Consider 8 trees whose heights from left to right are 5, 5, 3, 3, 3, 4, 5, 5, where every ui is 3 and every di is 2. Three climbs from the base of tree 1 with two rests in between put the worm on the top of tree 1 at second 5. It is on a top, so it does not rest, and from second 6 through second 9 it jumps to trees 2, 3, 4 and 5, landing on the top of each one and resting none of those times. At second 10 it jumps to tree 6 and stands at height 3, but the top of tree 6 is 4, so it rests at second 11 and slides to height 1. It climbs at second 12 to the top of tree 6, jumps at second 13 to tree 7 and stands at height 4, rests at second 14 down to height 2, climbs at second 15 to the top of tree 7 at height 5, and jumps at second 16 to tree 8, where height 5 is the top and the trip ends. That route takes 16 seconds, and it is not the fastest one. Jumping along the bases of all eight trees and climbing only the last one takes 19 seconds: a jump made below a top is always followed by a rest, and at height 0 the worm cannot slide any lower.
The first line has the number of test cases K. (1≤K≤10)
Each test case has four lines.
For each test case print one line with the shortest travel time in seconds. If the worm cannot reach the top of tree N, print NEVER in capital letters.