Least cost path in a sorted array

一世执手 提交于 2019-12-22 10:55:15

问题


Given a sorted array A e.g. {4,9,10,11,19}. The cost for moving from i->j is abs(A[j]-A[i]). Start from a given element e.g. 10. Find out the least cost path without visiting same element twice. So in this example solution would be 10->9->4->11->19 i.e. 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?


回答1:


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]



回答2:


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.



来源:https://stackoverflow.com/questions/19853293/least-cost-path-in-a-sorted-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!