Interview puzzle about traveling along a line segment

Here is an interesting question that I met:

You can simply say that on the number line of length M, where 0 < M <= 1,000,000,000, you have given whole pairs of points N( 1 < N <= 100,000). In each pair, the first point represents the object in which the object is currently located, and the second point represents where the object should be moved. (Keep in mind that the point secondmay be smaller than first).

Now suppose you start from a point 0and have a cart that can hold an object 1. You want to transfer all objects from their starting positions to the corresponding end positions, moving the smallest distance along the number line (rather than the offset). You must score a point M.

Now I tried to reduce this problem to a simpler problem. Honestly, I can't even think of brute force (possibly greedy) decision. However, my first thought was to translate the reverse movement into two forward movements, but this does not work in all cases.

I took out these test cases 3inenter image description here

: 12. red 0. 6 (distance = 6), red, green. 5 (distance = 1) green. 6 (distance = 1) red, , 9 (distance = 3), 10 (distance = 1), .

6 + 1 + 1 + 3 + 1 = 12, .

12, . .

- ?

+5
3

, , :

  • ,
  • ( )

, , , , ( , ​​ )

@templatetypedef:
HashTable . .
.

 1. Get next pair according to index from the line.
 2. If current pair exists in hashtable then place element to its target location.  
    2.a Remove pair from hashtable.  
    2.b Make current pair the target location. Then go to step 1  
 ELSE 
        Increment current index until you get a pair present in the hashtable. Go to step 2  
0

, (a, b), (c, d), (e, f), ..., , , abs(b - a) + abs(d - c) + abs(f - e) + ..., , , abs(b - a) + abs(c - b) + abs(d - c) + abs(e - d) + ....
, , , " " . node , , , . .

0

This is an asymmetric traveling salesman problem . You can think of it as a graph. The edges will be each (start, end) pair, one for each (0, start) and all other pairs (finish, start).

Assuming NP! = P, it will have an exponential expected runtime.

0
source

All Articles