题目:https://vjudge.net/problem/UVA-11059
set<int,greater<int> > s;
s中元素默认从大到小排列
ac代码:
#include <iostream>
#include <cmath>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <stdlib.h>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
using namespace std;
typedef long long ll;
int main()
{
ll n,s[20],i,j,num=0,mul;
//freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
while(scanf("%lld",&n)==1)
{
num++;
set<ll,greater<ll> > ans;
for(i=0;i<n;i++)
{
scanf("%lld", &s[i]);
ans.insert(s[i]);
}
for(i=0;i<n;i++)
{
mul=s[i];
for(j=i+1;j<n;j++)
{
mul*=s[j];
ans.insert(mul);
}
}
set<ll,greater<ll>>::iterator it=ans.begin();
printf("Case #%d: The maximum product is %lld.\n\n",num,*it<0?0:*it);
}
return 0;
}
网上的代码,思路不同:
#include<iostream>
#include<cstdio>
using namespace std;
long long num[100];
int main()
{
int n;
int cnt = 0;
while (cin >> n)
{
long long ans = 0;
for (int i = 0; i < n; ++i)
cin >> num[i];
for (int i = 1; i <= n; ++i) //i:子序列长度
{
for (int j = 0; j + i <= n; ++j) //j:子序列起点 (这里之前写j + i < n,怒跪)
{
long long tt = 1;
for (int k = j; k < j + i; ++k) //累乘
{
tt *= num[k];
}
//cout << tt << endl;
ans = max(ans, tt);
}
}
printf("Case #%d: The maximum product is %lld.\n\n", ++cnt, ans);
}
return 0;
}