UVA11059-Maximum Product(动态规划)

时间:2023-03-09 05:51:49
UVA11059-Maximum Product(动态规划)

Problem UVA11059-Maximum Product

Accept:4769  Submit:38713

Time Limit: 3000 mSec

UVA11059-Maximum Product(动态规划) Problem Description

Given a sequence of integers S = {S1, S2, . . . , Sn}, you should determine what is the value of the maximum positive product involving consecutive terms of S. If you cannot find a positive sequence, you should consider 0 as the value of the maximum product.

UVA11059-Maximum Product(动态规划) Input

Each test case starts with 1 ≤ N ≤ 18, the number of elements in a sequence. Each element Si is an integer such that −10 ≤ Si ≤ 10. Next line will have N integers, representing the value of each element in the sequence. There is a blank line after each test case. The input is terminated by end of file (EOF).

UVA11059-Maximum Product(动态规划) Output

For each test case you must print the message: ‘Case #M: The maximum product is P.’, where M is the number of the test case, starting from 1, and P is the value of the maximum product. After each test case you must print a blank line.

UVA11059-Maximum Product(动态规划) Sample Input

3 2 4 -3
5
2 5 -1 2 -1

UVA11059-Maximum Product(动态规划) Sample Ouput

Case #1: The maximum product is 8.

Case #2: The maximum product is 20.

题解:lrj给的是暴力的做法,不够这个题显然可以dp去做,维护两个dp数组,一个维护最大正值,一个维护最小负值,状态转移很简单,看代码就能明白。

P.S.原来之一用printf("%lld\n",x)来输出long long,这一次用了I64d输出,WA到怀疑人生,不知道为啥。(写这一篇题解就是为了记录这个WA点)

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long LL; const int maxn = ;
LL dp_max[maxn],dp_min[maxn];
int iCase = ; int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
int n;
while(cin >> n){
dp_max[] = dp_min[] = 0LL;
LL Max = ;
int x;
for(int i = ;i <= n;i++){
cin >> x;
if(x > ){
dp_max[i] = dp_max[i-]*x;
dp_min[i] = dp_min[i-]*x;
if(!dp_max[i]) dp_max[i] = x;
}
else if(x < ){
dp_max[i] = dp_min[i-]*x;
dp_min[i] = dp_max[i-]*x;
if(!dp_min[i]) dp_min[i] = x;
}
else{
dp_max[i] = dp_min[i] = 0LL;
}
if(Max < dp_max[i] && x) Max = dp_max[i];
}
printf("Case #%d: The maximum product is %lld.\n\n",iCase++,Max);
}
return ;
}