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.
AC代码
#include<bits/stdc++.h>
using namespace std;
const int maxn=10010;
#define ll long long
int n,s[20];
int main(){
int test=1;
while(scanf("%d",&n)!=EOF){
for(int i=0;i<n;i++){
scanf("%d",&s[i]);
}
ll ans=0;
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
ll cans=1;
if(i<=j)
for(int k=i;k<=j;k++){
cans*=s[k];
if(cans>ans)
ans=cans;
}
}
}
//输出
printf("Case #%d: The maximum product is %lld.\n\n",test++,ans);
}
return 0;
}
一点心得
写程序的时候,那些不执行的地方,就是自认为执行了也无所谓的地方,就不要让他执行。要么是循环的时候就考虑到这种情况,不要让他出来,要么是用判断语句屏蔽掉,这种不必要的执行往往会对程序造成一些影响,写代码要干净。
一个例子就是这道题里的循环,刚开始自己的思路是两个for循环确定左右界,然后再用一个循环求字序列的积,而且没有考虑左区间必须大于右区间,因为自认为如果i>j的话,就不满足循环的条件,自然就不执行,殊不知循环不执行,下边的判断会执行,就造成了cans==1这个例子的凭空出现。
这个想法一个是不干净,另一个就是复杂度是O(n3),这种复杂度不管在哪里都是要毙掉的好吗,所以枚举的方法就应该是两个循环这种枚举,再把边界考虑清楚。
Uva获取数据的方法
因为找不到自己哪里错了,所以就要获取数据。上uDebug网站,把自己输出与后台数据比对,看哪里错了
那么问题来了,怎样获取自己的数据呢?
#include <fstream>
ofstream write;
write.open("text.txt");
write<<"abc"<<endl;
write.close();
文件读写.