UVa 11059 - Maximum Product

题目:最大字段积。

分析:dp,最大字段和类似物。求解过程同最大字段和。

            这里注意,设置两个状态:以本元素结束时,最大正值和最小的负值。

            更新时,如果data[i]为正,则对应跟新,如果data[i]为负,则交叉跟新,

            data[i]为0时,当前最大值,最小值置零。

            本题数据较小,可以直接用O(n^2)暴力算法,枚举起始结束位置即可。

说明:用long long防止溢出。

#include 
#include 
#include 

using namespace std;

int data[20];

int main()
{
	int n,t = 1;
	while (cin >> n) {
		for (int i = 1 ; i <= n ; ++ i)
			cin >> data[i];
		long long max = 0,neg = 0,pos = 0,tem;
		for (int i = 1 ; i <= n ; ++ i) {
			if (data[i] == 0) 
				neg = pos = 0;
			else if (data[i] > 0) {
				pos = pos*data[i];
				neg = neg*data[i];
				if (!pos) pos = data[i];
			}else if (data[i] < 0) {
				tem = pos*data[i];
				pos = neg*data[i];
				neg = tem;
				if (!neg) neg = data[i];
			}
			if (max < pos && data[i])
				max = pos;
		}
		
		cout << "Case #" << t ++ << ": The maximum product is " << max << ".\n\n";	
	}
	return 0;
}


你可能感兴趣的:(解题报告,动态规划(DP))