算法学习1——动态规划

打算用这个星期学完基本的动态规划!加油。 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;
}

15.2矩阵链乘法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值