码迷,mamicode.com
首页 > 其他好文 > 详细

暴力求解最大乘积

时间:2015-07-29 20:58:40      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

 

题意:

      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 Output
Case #1: The maximum product is 8.


Case #2: The maximum product is 20.

 

思路分析:

           这道题关键在于给出计算的起点和终点。然后一直循环计算,最后再在所有的乘积中找到最大的数就KO了!

           注意:

           1、输出格式,空行

           2、数字比较大,用long long类型

源代码:

        

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string>
 4 #include<algorithm>
 5 using namespace std;
 6 int main()
 7 {
 8     int n;
 9     int count = 0;
10     while (scanf_s("%d",&n)!=EOF)            //输入方式
11     {
12         count++;
13         int a[25];
14         for (int i = 0; i < n; i++)
15             cin >> a[i];
16 
17         long long sum = 0;
18         long long m = 0;
19         for (int i = 0; i < n; i++)        //起始点
20         {
21             for (int j = i; j < n; j++)        //终点
22             {
23                 sum = 1;                           //每次一回合要重新开始
24 
25                 for (int k = i; k <= j; k++)
26                 {
27                     sum *= a[k];
28                     m = max(sum, m);                //找最大的数
29                 }
30             }
31         }
32     
33     printf("Case #%d: The maximum product is %lld.\n\n", count, m);
34     }
35     return 0;
36 }


 

心得:

       做完这个题目心得还真没有,总之把代码写得让别人看得懂就好。题目用了三个循环,前两个是给出起点跟终点,第三个是计算乘积,每次出来一个乘积,就用max函数保存最大的数。

       

        

 

     

暴力求解最大乘积

标签:

原文地址:http://www.cnblogs.com/Lynn0814/p/4687174.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!