1
+ """
2
+ An even number of trees are left along one side of a country road. You've been assigned the job to
3
+ plant these trees at an even interval on both sides of the road. The length L and width W of the road
4
+ are variable, and a pair of trees must be planted at the beginning (at 0) and at the end (at L) of
5
+ the road. Only one tree can be moved at a time. The goal is to calculate the lowest amount of
6
+ distance that the trees have to be moved before they are all in a valid position.
7
+ """
8
+
9
+ from math import sqrt
10
+ import sys
11
+
12
+ def planting_trees (trees , L , W ):
13
+ """
14
+ Returns the minimum distance that trees have to be moved before they are all in a valid state.
15
+
16
+ Parameters:
17
+ tree (list<int>): A sorted list of integers with all trees' position along the road.
18
+ L (int): An integer with the length of the road.
19
+ W (int): An integer with the width of the road.
20
+
21
+ Returns:
22
+ A float number with the total distance trees have been moved.
23
+ """
24
+ trees = [0 ] + trees
25
+
26
+ n_pairs = int (len (trees )/ 2 )
27
+
28
+ space_between_pairs = L / (n_pairs - 1 )
29
+
30
+ target_locations = [location * space_between_pairs for location in range (n_pairs )]
31
+
32
+ cmatrix = [[0 for _ in range (n_pairs + 1 )] for _ in range (n_pairs + 1 )]
33
+ for ri in range (1 , n_pairs + 1 ):
34
+ cmatrix [ri ][0 ] = cmatrix [ri - 1 ][0 ] + sqrt (W + abs (trees [ri ]- target_locations [ri - 1 ])** 2 )
35
+ for li in range (1 , n_pairs + 1 ):
36
+ cmatrix [0 ][li ] = cmatrix [0 ][li - 1 ] + abs (trees [li ]- target_locations [li - 1 ])
37
+
38
+ for ri in range (1 , n_pairs + 1 ):
39
+ for li in range (1 , n_pairs + 1 ):
40
+ cmatrix [ri ][li ] = min (
41
+ cmatrix [ri - 1 ][li ] + sqrt (W + (trees [li + ri ]- target_locations [ri - 1 ])** 2 ),
42
+ cmatrix [ri ][li - 1 ] + abs (trees [li + ri ]- target_locations [li - 1 ])
43
+ )
44
+
45
+ return cmatrix [n_pairs ][n_pairs ]
0 commit comments