-
Notifications
You must be signed in to change notification settings - Fork 0
/
cutting_rod.py
175 lines (157 loc) · 1.67 KB
/
cutting_rod.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
'''
Dynamic Programming:
not adding c++ files for now. Will add soon
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.
Input Format:
---------------
1 5 8 9 10 17 17 20
1 2 3 4 5 6 7 8
total no of enteries are the length of the rod
Algo strategy:
-Create the possible permutations in which the rod can be cut up and add up the max vals
How:
val(l) = max{{ val(l-r)+val(r) } for r in range(0, l)}
# output:
non memoized:
1 1
1 5
1 8
1 1
1 1
5 5
1 10
1 1
1 1
1 5
5 8
1 13
1 1
1 1
1 5
1 8
1 1
1 1
5 5
5 10
1 1
1 5
1 1
1 5
8 8
1 17
1 1
1 1
1 5
1 8
1 1
1 1
5 5
1 10
1 1
1 1
1 5
5 8
5 13
1 1
1 5
1 1
1 5
1 8
1 1
1 1
5 5
8 10
1 18
1 1
1 1
1 5
1 8
1 1
1 1
5 5
1 10
1 1
1 1
1 5
5 8
1 13
1 1
1 1
1 5
1 8
1 1
1 1
5 5
5 10
1 1
1 5
1 1
1 5
8 8
5 17
1 1
1 5
1 1
1 5
1 8
1 1
1 1
5 5
1 10
1 1
1 1
1 5
5 8
8 13
1 1
1 5
1 8
1 1
1 1
5 5
1 1
1 5
1 8
1 1
1 1
5 5
10 10
22
memoized:
lesser no of calls
1 1
1 5
1 8
5 5
1 10
5 8
1 13
5 10
8 8
1 17
5 13
8 10
1 18
5 17
8 13
10 10
22
'''
# haha memoized code for rod cutting
s = list(map(int, input().split(" ")))
m = {}
def solve(l):
if l in m:
return m[l]
val = []
val.append(s[l-1])
if(l == 1):
m[1] = s[0]
return m[1]
for i in range(1, int(l/2)+1):
a, b = solve(i), solve(l-i)
print(a," ", b)
val.append(( a+b ))
m[l] = max(val)
return m[l]
print(solve(8))