[TopCoder]SRM 645 Div2 Connecting Cars


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.



给定车厢的位置和距离的元组。对于每一个i,有一节长度为lengths[i]米的车厢停靠在距离起点positions[i]米处。(换言之,这节车厢的起止坐标为positions[i], positions[i]+lengths[i])






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[0] )
        ans = 0
        mid = size / 2
        start = segments[mid][0]
        for x in range(mid - 1, -1, -1):
            ans += start - segments[x][1]
            start -= segments[x][1] - segments[x][0]
        end = segments[mid][1]
        for x in range(mid + 1, size):
            ans += segments[x][0] - end
            end += segments[x][1] - segments[x][0]
        return ans



如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码


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


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