算法导论-第15章-动态规划:钢条切割问题自底向下方法C++实现

#include 
#include 
#include 
using namespace std;

int cut_rod(int P[], int R[], int M[], int size) {
	int i{};
	int j{};
	for (i = 1; i < size; ++i) {
		int max{ -1 };
		int max_index{ -1 };
		for (j = 1; j <= i; ++j) {
			int tmp{};
			if ((tmp = P[j] + R[i - j]) > max) {
				max = tmp;
				max_index = j;
			}
		}
		R[i] = max;
		M[i] = max_index;
	}
	return R[size - 1];
}

int main(int argc, char* argv[]) {
	vector v{};
	cout << "please input the value of all kinds of length :" << endl;
	int element{};
	while (cin >> element) {
		v.push_back(element);
	}
	int* R = new int[v.size() + 1] {};
	int* P = new int[v.size() + 1] {};
	int* M = new int[v.size() + 1] {};
	int index{};
	for_each(v.begin(), v.end(), [=](int x)mutable{ P[++index] = x; });
	int result = cut_rod(P, R, M, v.size() + 1);
	cout << "the best cut is :" << endl;
	int length = v.size();
	for (int i = M[v.size()]; !i;) {
		cout << i << " ";
		length -= i;
		i = M[length];
	}
	cout << endl;
	cout << "and the sum of value is : " << result << endl;
	delete[]R;
	delete[]P;
	delete[]M;
	return 0;
}

你可能感兴趣的:(算法)