B. Maximum Product(贪心+构造)Codeforces Round #670 (Div. 2)
原题链接: http://codeforces.com/contest/1406/problems
测试样例
input
4
5
-1 -2 -3 -4 -5
6
-1 -2 -3 1 2 -1
6
-1 0 0 0 -1 -1
6
-9 -7 -5 -3 -2 1
output
-120
12
0
945
Note
In the first test case, choosing a1,a2,a3,a4,a5 is a best choice: (−1)⋅(−2)⋅(−3)⋅(−4)⋅(−5)=−120.
In the second test case, choosing a1,a2,a3,a5,a6 is a best choice: (−1)⋅(−2)⋅(−3)⋅2⋅(−1)=12.
In the third test case, choosing a1,a2,a3,a4,a5 is a best choice: (−1)⋅0⋅0⋅0⋅(−1)=0.
In the fourth test case, choosing a1,a2,a3,a4,a6 is a best choice: (−9)⋅(−7)⋅(−5)⋅(−3)⋅1=945.
题意: 给你一个整数序列,请你从中选五个不同下标的数,使得它们的乘积最大。
解题思路: 这道题十分简单,利用贪心思想即可,不用在乎其内部构造,我们只需要进行一次排序,按照我们的思维,由于有负数,所以我们选的五个数尽量让负数的数量为偶数(如果不可那就只能为奇数)。知道这个,我们接下来就是构造了,要想五个数的乘积最大,我们自然会想到每个元素的绝对值最大(我们暂且认为负数的数量都是偶数。),那么我们排序之后自然就会选取后面的数和前面的数。(它们的绝对值都很大。),OK,我们枚举取数情况选取最大值即可。
AC代码
/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h> //POJ不支持
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
int t,n;
ll a[maxn];
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>t){
while(t--){
cin>>n;
rep(i,0,n-1){
cin>>a[i];
}
sort(a,a+n);
ll ans=(1e18)*(-1);
rep(i,1,3){
if(i==1){
ans=max(ans,a[0]*a[1]*a[n-1]*a[n-2]*a[n-3]);
}
else if(i==2){
ans=max(ans,a[n-1]*a[n-2]*a[n-3]*a[n-4]*a[n-5]);
}
else{
ans=max(ans,a[0]*a[1]*a[2]*a[3]*a[n-1]);
}
}
cout<<ans<<endl;
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)