Problem D - Maximum Product
Time Limit: 1 second
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.
Problem setter: Sérgio Queiroz de Medeiros
#include <cstdio>
int S[20];
int num_count = 0;
int main()
{
long long max_product = 0;
int g_count = 1;
while(scanf("%d", &num_count) == 1)
{
max_product = 0;
for(int i = 0; i < num_count; i++)
scanf("%d", &S[i]);
// 计算所有连续整数的乘积
for(int i = 0; i < num_count; i++)
{
long long sub_product = S[i];
if(sub_product > max_product)
max_product = sub_product;
for(int j = i+1; j < num_count; j++)
{
sub_product *= S[j];
if(sub_product > max_product)
max_product = sub_product;
}
}
printf("Case #%d: The maximum product is %lld.\n\n", g_count, max_product);
g_count++;
}
return 0;
}这题枚举所有可能性就可以了,一开始老是通不过,后来查了答案才注意到,整个乘积可以达到10^18,超过了int范围,改用long long即可。
这里需要记住:int大概表示10位整数,最大为21亿左右,long long大概表示19位整数。
本文介绍了一个编程问题——寻找给定整数序列中最大的连续正数乘积,并提供了一种解决方案。通过枚举所有可能的连续子序列并计算其乘积来找出最大值。需要注意的是,由于乘积可能很大,使用long long类型来存储结果。
394

被折叠的 条评论
为什么被折叠?



