Janusz works in roller coaster maintenance. The station of the roller coaster is a long straight segment of railroad tracks. There are some cars on those tracks. The cars are currently not attached to each other, and there may be gaps between some of them. Janusz has to push them all together and connect them into a train.
You are given the tuple (integer)s positions and lengths. For each valid i, there is a car that is lengths[i] meters long and starts positions[i] meters from the beginning of the station. (In other words, the coordinates currently occupied by this car are in the interval from positions[i] to positions[i]+lengths[i].)
Moving a single car one meter in either direction costs Janusz one unit of energy. Compute the smallest total amount of energy sufficient to push all cars together. In the final configuration the cars must be located one after another with no gaps between them.
(Note that there is no restriction on the movement of cars or on the final position of the train. Janusz may push the cars in any order, and he may even push some cars by a non-integer number of meters if he wants to.)
- You may assume that the optimal answer is always an integer that fits into a signed 64-bit integer data type.
- lengths and positions will have the same number of elements.
- lengths will have between 2 and 50 elements, inclusive.
- Each element of lengths and positions will be between 1 and 10^9, inclusive.
- The segments occupied by the cars may touch but they will not overlap.
The geometric median of a discrete set of sample points in a Euclidean space is the point minimizing the sum of distances to the sample points.
For the 1-dimensional case, the geometric median coincides with the median. This is because the univariate median also minimizes the sum of distances from the points.
class ConnectingCars: def minimizeCost(self, positions, lengths): size = len(positions) segments = [( positions[x], positions[x] + lengths[x] ) for x in range(size)] segments = sorted( segments, key = lambda x : x ) ans = 0 mid = size / 2 start = segments[mid] for x in range(mid - 1, -1, -1): ans += start - segments[x] start -= segments[x] - segments[x] end = segments[mid] for x in range(mid + 1, size): ans += segments[x] - end end += segments[x] - segments[x] return ans