Fundamental Algorithms Analysis(008)-Cut Rod[강철 막대 절단 문제/정장 분배][C++/Java]

Cut Rod
Plain recursive method
int cutRod(map<int,int> list,int n) {
	if (n == 0) return 0;
	int q = INT_MIN;
	for (int i = 1; i <= n; ++i) q = max(q, list[i] + cR1(list,n - i));
	return q;
}

Improved recursive
I like search in table.시 계 를 찾 는 것 이 더 빠 를 것 입 니 다!
vector<int> table(99999, INT_MIN);
int cutRod(map<int, int> list, int n) {
	if (table[n] >= 0) return table[n];// If exists, search from table
	if (n == 0) return table[0] = 0;
	int q=INT_MIN;
	for (int i = 1; i <= n; ++i)q = max(q, list[i] + cutRod(list, n - i));
	return table[n]=q;//Store new value
}

Dynamic Programming method
Still table! 시 계 를 끝까지 조사 하 라!
vector<int> table(99999,0);
int cutRod(map<int, int> list, int n) {
	for (int i = 1; i <= n; ++i) {
		int q = INT_MIN;
		for (int j = 1; j <= i; ++j) q = max(q, list[j] + table[i - j]);
		table[i] = q;
	}
	return table[n];
}

Main test(C++)
#include 
#include 
#include 
#include 
using namespace std;
int cR1(map<int,int> list,int n) {
	if (n == 0) return 0;
	int q = INT_MIN;
	for (int i = 1; i <= n; ++i) q = max(q, list[i] + cR1(list,n - i));
	return q;
}
vector<int> table1(99999, INT_MIN);
int cR2(map<int, int> list, int n) {
	if (table1[n] >= 0) return table1[n];// If exists, search from table
	if (n == 0) return table1[0] = 0;
	int q=INT_MIN;
	for (int i = 1; i <= n; ++i)q = max(q, list[i] + cR2(list, n - i));
	return table1[n]=q;//Store new value
}
vector<int> table2(99999, 0);
int cR3(map<int, int> list, int n) {
	for (int i = 1; i <= n; ++i) {
		int q = INT_MIN;
		for (int j = 1; j <= i; ++j) q = max(q, list[j] + table2[i - j]);
		table2[i] = q;
	}
	return table2[n];
}
int main() {
	map<int, int> list{ {1,1},{2,5},{3,8},{4,9},{5,10},{6,17},{7,17},{8,20},{9,24},{10,30} };
	cout<<cR3(list, 7);
}

좋은 웹페이지 즐겨찾기