I have the next problem I'm having a hard time solving.
I have a straight line , and a list of M villages on it. I need to allocate the N railway stations in these villages, so that the average distance of a village from a railway station, will be minimized.
example:
villages: -----1--------------2--3---------4--5------------6----------7---
and we have 3 railway stations.
tried to use dynamic programming, but couldn't do it. can anyone suggest a way to solv this problem? (except the obvious way of trying all the options)?
I assume that, for each village, you care only about the distance from that village to a particular railway station, not all railway stations. So if you could put a railway station in each village the "average distance from a village to a railway station" would be zero, even if the villages were thousands of miles apart, so that the distance from one village to a different railway station in a different village would be large.
If you have a group of villages which must all use the same railway station then the best position for that railway station is the median position on the line of the villages (if the number of villages is odd) or anywhere between the middle two villages in the line (if the number of villages is even). This is because if the railway station is anywhere else, moving it towards the median will shorten the distance to the majority of the villages in the group, while increasing the distance only to the minority.
So an easy approach to this problem is to work out how to divide the M villages into N groups of contiguous villages, each served by a railway station, placed at the median village, or anywhere between the two most central villages in the group.
This is a dynamic programming problem where you work along the line of villages, computing at village k the best way to divide those k villages up into j groups, and the cost of that best way. You can do this by checking, for each i, of the cost of creating a group from the last i villages and adding on the cost of creating j-1 groups from the first k - i villages.
If you really mean the average distance between every village and every railway station then note you can just deal with the railway stations one at a time, because the position of one railway station does not affect the cost of positioning another railway station. Then you get N railway stations built on top of each other at the median, or placed along the strip between the two central villages, if there are an even number of villages - which doesn't really make sense.