题意:
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. ", count, m); 34 } 35 return 0; 36 }
心得:
做完这个题目心得还真没有,总之把代码写得让别人看得懂就好。题目用了三个循环,前两个是给出起点跟终点,第三个是计算乘积,每次出来一个乘积,就用max函数保存最大的数。