打算用这个星期学完基本的动态规划!加油。 2019/3/28
15.1 钢条切割
//递归求法, n = 30以后超级慢
#include <cstdio>
#include <iostream>
#define MIN -100000
using namespace std;
int max(int a, int b) {
return (a>b)?a:b;
}
int CUT_ROD(int n, int p[]) {
int q = MIN;
if(n == 0) return 0;
for(int i = 1; i <= n; i++) q = max(q, p[i] + CUT_ROD(n - i, p));
return q;
}
int main () {
int p[100] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
int n;
while(~scanf("%d", &n)) {
printf("%d\n", CUT_ROD(n, p));
}
return 0;
}
//自上而下的求解,带备忘录
#include <cstdio>
#include <iostream>
#define MIN -100000
using namespace std;
int max(int a, int b) {
return (a>b)?a:b;
}
int MEMOIZED_CUT_ROD(int p[], int n, int arr[]) {
int q = MIN, i;
if(arr[n] >= 0) return arr[n];
if(n == 0) q = 0;
else {
for(i = 1; i <= n; i++) {
q = max(q, p[i] + MEMOIZED_CUT_ROD(p, n - i, arr));
}
}
arr[n] = q;
return q;
}
int main () {
int p[100] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
int n, i;
while(~scanf("%d", &n)) {
int arr[100], ans;
for(i = 0; i <= n; i++) arr[i] = MIN;
ans = MEMOIZED_CUT_ROD(p, n, arr);
cout << ans << endl;
}
return 0;
}
//自下而上的求解
#include <cstdio>
#include <iostream>
#define MIN -100000
using namespace std;
int max(int a, int b) {
return (a>b)?a:b;
}
int BOTTOM_UP_ROD(int p[],int n,int arr[]) {
int i, j;
int q;
for(j = 1; j <= n; j++) {
q = MIN;
for(i = 1; i <= j; i++) {
q = max(q, p[i] + arr[j-i]);
}
arr[j] = q;
}
return arr[n];
}
int main () {
int p[100] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
int n;
while(~scanf("%d", &n)) {
int arr[100] = {0}, ans;
ans = BOTTOM_UP_ROD(p, n, arr);
cout << ans << endl;
}
return 0;
}
//重构解, 输出切割方式
#include <cstdio>
#include <iostream>
#define MIN -100000
using namespace std;
int max(int a, int b) {
return (a>b)?a:b;
}
int EXTENDED_BOTTOM_UP_ROD(int p[],int n,int arr[],int s[]) {
int i, j;
int q;
for(j = 1; j <= n; j++) {
q = MIN;
for(i = 1; i <= j; i++) {
if(q < max(q, p[i] + arr[j-i])) {
q = max(q, p[i] + arr[j-i]);
s[j] = i;
}
}
arr[j] = q;
}
return arr[n];
}
void PRINT_CUT_ROD_SOLUTION(int s[], int n) {
while(n > 0) {
cout << s[n] << ' ';
n = n - s[n];
}
cout << endl;
}
int main () {
int p[100] = {0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
int n, i;
while(~scanf("%d", &n)) {
int arr[100] = {0}, ans, s[100] = {0};
ans = EXTENDED_BOTTOM_UP_ROD(p, n, arr, s);
cout << ans << endl;
PRINT_CUT_ROD_SOLUTION(s, n);
}
return 0;
}