Falling Ice

Time limit1sMemory limit128 MB

Summary
Simulate disks falling one at a time into a box, each settling at the lowest reachable resting spot, and report the final pile height.
Level

Medium7 of 10

Topics
Geometry, Simulation, Implementation, Brute force
Solved
No attempts yet

Problem

Disks of ice fall one at a time into a box. Each disk drops straight down and comes to rest at the lowest position it can reach without overlapping any disk already in the box and without moving any of them. Once a disk stops it freezes in place and can never be pushed by a later disk. Your task is to compute the total height of the final pile of disks.

To make the answer unique, assume that any disk which reaches the bottom of the box rolls as far to the left as it can. The input is also chosen so that every disk which does not reach the bottom has a single, unambiguous lowest resting position, and so that there are no exact fits: each disk that settles touches exactly two supports (previously placed disks, or the walls and floor of the box).

Note that a disk cannot always reach the lowest empty spot in the box. Because a disk falls from the top, it may become wedged between an earlier disk and a wall (or between two earlier disks) even when there is still room lower down. It simply cannot get there by falling.

You can find the upper intersection point of two overlapping circles as follows. Let circle 1 have center (x1,y1)(x_1, y_1) and radius r1r_1, and let circle 2 have center (x2,y2)(x_2, y_2) and radius r2r_2, with circle 1 to the left of circle 2 (that is, x1<x2x_1 < x_2). Define

  • dx=x2−x1dx = x_2 - x_1,
  • dy=y2−y1dy = y_2 - y_1,
  • D=dx2+dy2D = \sqrt{dx^2 + dy^2},
  • E=r12−r22+D22DE = \dfrac{r_1^2 - r_2^2 + D^2}{2D},
  • F=r12−E2F = \sqrt{r_1^2 - E^2}.

Then the upper intersection point is

(x1+E dx−F dyD,  y1+F dx+E dyD).\left(x_1 + \frac{E\,dx - F\,dy}{D},\; y_1 + \frac{F\,dx + E\,dy}{D}\right).

Input

The input consists of one or more data sets, followed by a line containing only 00 that marks the end of the input. Each data set is given on its own line as a sequence of three or more blank-separated positive integers in the form w n d1 d2 … dnw\ n\ d_1\ d_2\ \dots\ d_n, where ww is the width of the box, nn is the number of disks, and d1,d2,…,dnd_1, d_2, \dots, d_n are the diameters of the disks in the order in which they fall into the box. You may assume that w<100w < 100, that n<10n < 10, and that every diameter is smaller than ww.

Output

For each data set, print a single line containing the height of the pile of disks, rounded to two digits after the decimal point.

Examples2

  1. Example 1

    Input
    10 3 5 2 3 
    8 2 5 5 
    11 3 10 2 4 
    9 3 4 4 6 
    10 6 5 4 6 3 5 2 
    0 
    
    Expected output
    5.00
    9.00
    12.99
    9.58
    14.19
    
  2. Example 2

    Input
    10 1 6
    0
    
    Expected output
    6.00