programming-challenges Cutting Sticks (111105) 题解

和算法导论中动态规划章节中计算矩阵相乘最小代价是一样的解题思路。稍有的一次ac,所以难度只到2吧。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

const int NUM = 1010; 
int nums[NUM][NUM];

int main() {
	int l = 0; 

	while (cin >> l && l > 0) {
		int n = 0; cin >> n; 
		vector<int> ranges(n + 1); 
		for (int i = 0; i < n; i++) {
			cin >> ranges[i]; 
		}
		ranges[n] = l;

		for (int i = n; i > 0; i--) {
			ranges[i] = ranges[i] - ranges[i - 1];
		}
		
		memset(nums, 0, sizeof(nums));
		
		for (int len = 1; len <= n; len++) {
			for (int start = 0; start <= n - len; start++) {
				int end = start + len; 
				int minVal = 0x7fffffff;
				int totalVal = 0; 
				for (int i = start; i <= end; i++) {
					totalVal += ranges[i];
				}
				for (int i = 0; i < (end - start); i++) {
					minVal = min(minVal, totalVal + nums[start][start + i] + nums[start + i + 1][end]);
				}
				nums[start][end] = minVal;
			}
		}

		cout << "The minimum cutting is " << nums[0][n] << "." << endl;
		
	}

	return 0; 
}


你可能感兴趣的:(Algorithm,C++,动态规划)