-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrod_cutting.cpp
More file actions
97 lines (79 loc) · 2.45 KB
/
rod_cutting.cpp
File metadata and controls
97 lines (79 loc) · 2.45 KB
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
#include "rod_cutting.h"
#include <algorithm>
#include <limits>
auto RodCutting::CutRod(const std::map<int, int>& price, const int length) -> int
{
if (length == 0)
{
return 0;
}
int max_revenue = std::numeric_limits<int>::min();
for (int i = 1; i <= length; ++i)
{
max_revenue = std::max(max_revenue, price.at(i) + CutRod(price, length - i));
}
return max_revenue;
}
auto RodCutting::MemoizedCutRod(const std::map<int, int>& price, const int length) -> int
{
std::vector<int> memo(static_cast<int>(price.size()) + 1, -1);
return MemoizedCutRodAux(price, length, memo);
}
auto RodCutting::MemoizedCutRodAux(const std::map<int, int>& price, const int length, std::vector<int>& memo) -> int
{
int max_revenue = std::numeric_limits<int>::min();
if (memo[length] >= 0)
{
return memo[length];
}
if (length == 0)
{
max_revenue = 0;
}
else
{
for (int i = 1; i <= length; ++i)
{
max_revenue = std::max(max_revenue, price.at(i) + MemoizedCutRodAux(price, length - i, memo));
}
}
memo[length] = max_revenue;
return max_revenue;
}
auto RodCutting::BottomUpCutRod(const std::map<int, int>& price, const int length) -> int
{
std::vector<int> memo(static_cast<int>(price.size()) + 1, -1);
memo[0] = 0;
for (int i = 1; i <= length; ++i)
{
int max_revenue = std::numeric_limits<int>::min();
for (int j = 1; j <= i; ++j)
{
max_revenue = std::max(max_revenue, price.at(j) + memo[i - j]);
}
memo[i] = max_revenue;
}
return memo[length];
}
auto RodCutting::ExtendedBottomUpCutRod(const std::map<int, int>& price, const int length) -> std::tuple<int, int>
{
// the memoization of the max revenue
std::vector<int> memo(static_cast<int>(price.size()) + 1, -1);
memo[0] = 0;
// the optimal size of the first piece to cut off
std::vector<int> optimal_first_piece(static_cast<int>(price.size()) + 1, -1);
for (int i = 1; i <= length; ++i)
{
int max_revenue = std::numeric_limits<int>::min();
for (int j = 1; j <= i; ++j)
{
if (max_revenue < price.at(j) + memo[i - j])
{
max_revenue = price.at(j) + memo[i - j];
optimal_first_piece[i] = j;
}
}
memo[i] = max_revenue;
}
return std::make_tuple(memo[length], optimal_first_piece[length]);
}