To calculate costs, you just need to summarize all regional costs. For example, for a route 3 -> 1 -> 2 -> 4 -> 5 -> 3this gives
(3,1) => 3
(1,2) => 20
(2,4) => 4
(4,5) => 3
(5,3) => 7
------------
sum 37
So, in essence, you need to create the first sample of the route and calculate its cost. Once you do this, you know that the bottom line may be the best solution.
, , , , , , .
. , 1 2 3 4 5 6 7 8 9 1 40. , - , : 1 2 4 5 6 ... , 41. , - , , 40 , , ! , 1 2 4 5 6.
( , !)