UVA11059-Maximum Product(动态规划)

Problem UVA11059-Maximum Product

Accept:4769  Submit:38713

Time Limit: 3000 mSec

 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.

 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).

 

 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.

 

 Sample Input

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

 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点)

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 using namespace std;
 6 typedef long long LL;
 7 
 8 const int maxn = 25;
 9 LL dp_max[maxn],dp_min[maxn];
10 int iCase = 1;
11 
12 int main()
13 {
14     //freopen("input.txt","r",stdin);
15     //freopen("output.txt","w",stdout);
16     int n;
17     while(cin >> n){
18         dp_max[0] = dp_min[0] = 0LL;
19         LL Max = 0;
20         int x;
21         for(int i = 1;i <= n;i++){
22             cin >> x;
23             if(x > 0){
24                 dp_max[i] = dp_max[i-1]*x;
25                 dp_min[i] = dp_min[i-1]*x;
26                 if(!dp_max[i]) dp_max[i] = x;
27             }
28             else if(x < 0){
29                dp_max[i] = dp_min[i-1]*x;
30                dp_min[i] = dp_max[i-1]*x;
31                if(!dp_min[i]) dp_min[i] = x;
32             }
33             else{
34                 dp_max[i] = dp_min[i] = 0LL;
35             }
36             if(Max < dp_max[i] && x) Max = dp_max[i];
37         }
38         printf("Case #%d: The maximum product is %lld.\n\n",iCase++,Max);
39     }
40     return 0;
41 }

 

posted on 2018-08-25 19:52  随缘&不屈  阅读(579)  评论(0编辑  收藏  举报

导航