-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRodCuttingProblemLecture24.cpp
More file actions
91 lines (86 loc) · 2.21 KB
/
Copy pathRodCuttingProblemLecture24.cpp
File metadata and controls
91 lines (86 loc) · 2.21 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
#include <vector>
#include <iostream>
using namespace std;
int solve1(int ind ,int n,vector<int> &price,vector<vector<int>> &dp)
{
if(ind == 0)
{
return n*price[0];
}
if(dp[ind][n] != -1) return dp[ind][n];
int notTake = solve1(ind-1,n,price,dp);
int take = INT_MIN;
int rodlength = ind + 1;
if(rodlength <= n) take = price[ind] + solve1(ind,n-rodlength,price,dp);
return dp[ind][n] = max(notTake,take);
}
int solve2(vector<int> &price, int n)
{
vector<vector<int>> dp(n,vector<int>(n+1,-1));
for(int N = 0;N <= n;N++)
{
dp[0][N] = N*price[0];
}
for(int ind = 1;ind < n;ind++)
{
for(int N = 0;N <= n;N++)
{
int notTake = dp[ind-1][N];
int take = INT_MIN;
int rodlength = ind + 1;
if(rodlength <= N) take = price[ind] + dp[ind][N-rodlength];
dp[ind][N] = max(notTake,take);
}
}
return dp[n-1][n];
}
int solve3(vector<int> &price, int n)
{
// vector<vector<int>> dp(n,vector<int>(n+1,-1));
vector<int> prev(n+1,0),cur(n+1,0);
for(int N = 0;N <= n;N++)
{
prev[N] = N*price[0];
}
for(int ind = 1;ind < n;ind++)
{
for(int N = 0;N <= n;N++)
{
int notTake = prev[N];
int take = INT_MIN;
int rodlength = ind + 1;
if(rodlength <= N) take = price[ind] + cur[N-rodlength];
cur[N] = max(notTake,take);
}
prev = cur;
}
return prev[n];
}
int solve4(vector<int> &price, int n)
{
vector<int> prev(n+1,0);
for(int N = 0;N <= n;N++)
{
prev[N] = N*price[0];
}
for(int ind = 1;ind < n;ind++)
{
for(int N = 0;N <= n;N++)
{
int notTake = prev[N];
int take = INT_MIN;
int rodlength = ind + 1;
if(rodlength <= N) take = price[ind] + prev[N-rodlength];
prev[N] = max(notTake,take);
}
}
return prev[n];
}
int cutRod(vector<int> &price, int n)
{
// vector<vector<int>> dp(n,vector<int>(n+1,-1));
// return solve1(n-1,n,price,dp);
// return solve2(price,n);
// return solve3(price,n);
return solve4(price,n);
}