Faucet Flow

Interview

Time limit1sMemory limit128 MB

Summary
Water pours at 1 cubic unit per second into a 1-wide tank with vertical dividers of given heights; find the time when it first overflows the outermost divider.
Level

Medium7 of 10

Topics
Simulation, Implementation, Math, Greedy
Solved
No attempts yet

Problem

A faucet is pouring water into a long, thin aquarium that contains several vertical dividers (walls). The aquarium starts out empty and its bottom is perfectly level. How long will it take before water spills over the left-most or the right-most divider?

The faucet sits directly above the point x=0x = 0. The dividers stand at the odd positions x=−1,−3,−5,…x = -1, -3, -5, \ldots on the left (the left-most one at leftx) and x=1,3,5,…x = 1, 3, 5, \ldots on the right (the right-most one at rightx). Each divider is attached perpendicular to the floor and to the sides of the aquarium, and the dividers have various heights. The aquarium is longer than the span from leftx to rightx, its outer walls are taller than the tallest divider, and it is 11 unit wide everywhere. Water pours from the faucet at a rate of 11 cubic unit per second.

Assume the water is an ideal liquid: it always flows downhill, and when it cannot flow downhill it spreads at an equal rate in all horizontal directions.

Input

Each test case begins with two integers leftx (an odd number ≤−1\le -1) and rightx (an odd number ≥1\ge 1). The following values give the height (a positive integer) of each divider, listed from left to right. A test case has at most 10001000 dividers. The input ends with a line containing two zeros, which is not processed.

Output

For each test case, print a single integer: the number of seconds that pass before water first spills over either the left-most or the right-most divider.

Examples4

  1. Example 1

    Input
    -1 1
    3 5
    -3 3
    4 3 2 1
    -3 5
    1 2 2 1 1
    0 0
    
    Expected output
    6
    6
    8
    
  2. Example 2

    Input
    -1 1
    2 9
    0 0
    
    Expected output
    4
    
  3. Example 3

    Input
    -1 1
    5 5
    0 0
    
    Expected output
    10
    
  4. Example 4

    Input
    -1 1
    1 1
    -1 3
    5 1 10
    0 0
    
    Expected output
    2
    20