简体   繁体   中英

Least cost path in a sorted array

Given a sorted array A eg {4,9,10,11,19} . The cost for moving from i->j is abs(A[j]-A[i]) . Start from a given element eg 10 . Find out the least cost path without visiting same element twice. So in this example solution would be 10->9->4->11->19 ie 1 + 5 + 7 + 8 = 21 .

I tried to solve this using nearest neighbor approach.

 i = start;
 While (array is not empty)
    ldiff = A[i] - A[i-1]
    rdiff = A[i+1] - A[i]
    (ldiff < rdiff) ? sum += ldiff : sum += rdiff
    remove A[i]

This solution does not work in every case. I have realised that this is TSP problem. What could be the best approach to solve this problem? Shall I use TSP heuristics like Christofides or some other algorithm?

for your case least cost is 21, see

10->9->4->11->19 ==>  1 + 5 + 7 + 8 = 21.

I think, for common case, if you start from i-th position, least cost is path, minimum of

A[i]->A[i-1]-> ...->A[1] -> A[i+1] -> A[i+2] -> ...->A[n]  and

A[i]->A[i+1]-> ... ->A[n] ->A[i-1] ->A[i-2] -> ...->A[1]

Process either the smaller or the largest element, depending which is closer (in value, not index) to the starting element, then simply process the remaining elements to the right or to the left (depending on whether we processed the smallest or the largest element).

So, given 4,9,10,11,19 starting from 10 :

The distance from 10 to the smallest element 4 is 6, the distance from 10 to the largest element 19 is 9, so move to 4 .

Then process the remaining elements in sorted order - 9, 11, 19 .

This gives us 10 -> 4 -> 9 -> 11 -> 19 , which costs 6 + 5 + 2 + 8 = 21 .

This can be done in O(n) .

Note:

It's worth noting that as long as we first move towards the closest side, then towards the other side (regardless of which elements we process when, as long as we don't change direction more than once), we'll get an optimal result.

That's why 10 -> 9 -> 4 -> 11 -> 19 also gives 21 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM