## 题目描述：

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.)

Notes

-    You may assume that the optimal answer is always an integer that fits into a signed 64-bit integer data type.

Constraints

-    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.

## Python代码：

``````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
`````` Pingbacks已关闭。

1. 香港云主机 发布于 2015年1月16日 11:21 #

嗯，看看，支持支持！

2. seo 发布于 2015年4月18日 12:47 #

来看看。顺便给你增加点访问量[嘻嘻]