Minimum Path to Travel (N-1) 1D Points

时间:2016-08-31 12:16:27

标签: algorithm

In order to travel to all (N-1) points, one would usually use a MST / Travelling Sales Man problem, but I found an equation that needs explanation for calculating such in O(1) for 1D points.

min( min(abs(b[0]-a) + b[n-2]-b[0], abs(b[n-2]-a) + b[n-2]-b[0]), min( abs(b[1]-a) + b[n-1]-b[1], abs(b[n-1]-a) + b[n-1] - b[1]))

Where b[] is the array of the given points and a is the starting location.
The source of the problem and the equation are from Codeforces:

http://codeforces.com/contest/709/status/B

I would appreciate any help explaining this mathematical maneuver.

1 个答案:

答案 0 :(得分:0)

嗯,看problem definition,它没有提到点的输入按某种顺序排序。
只有当您首先排序输入点,然后是,通过计算此等式找到最小路径为O(1)时,才可能提供给出的方式。但是,总运行时复杂度将为O(nlogn)。

等式的解释:
可以把它想象成连续的所有点(排序后)。您有一个起点,您需要访问n-1点,这意味着您需要访问除了一个点以外的所有点。由此我们知道最小路径将是两者之一:

  1. 除第一个之外的所有要点
  2. 除最后一个之外的所有要点
  3. 你给出的等式完全计算出来。