题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5504
官方题解:
注意先特判
0
的情况:如果读入的数据有
0
,那么去掉所有的
0
且最后答案和
0
取一个max。剩下的正数显然全部乘起来比较优。对于负数的话,如果个数是奇数个我们就去掉绝对值最小的那一个,然后全部乘起来即可。
这题坑很多,要讨论的情况很多。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn = 65;
int n;
LL a[maxn];
bool cmp(int a,int b)
{
return a > b;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int i,zero = 0,pos = 0,neg = 0;
scanf("%d",&n);
for(i = 1; i <= n; i++)
{
scanf("%lld",&a[i]);
if(a[i] == 0) zero++;
if(a[i] > 0) pos++;
if(a[i] < 0) neg++;
}
if(n == 1 || zero == n)
{
printf("%lld\n",a[1]);
continue;
}
sort(a+1,a+1+n,cmp);
LL ans = 1;
if(pos == 0)
{
}
for(i = 1; i <= n; i++)
{
if(a[i] > 0)
ans *= a[i];
if(a[i] < 0) break;
}
int num = n - i + 1;
if(num % 2 == 1) //奇数个负数
{
if(num == 1 && pos == 0) ans = a[n];
for(int j = n; j > i; j--)
ans *= a[j];
}
else //偶数个负数
{
for(int j = i; j <= n; j++)
ans *= a[j];
}
if(zero && ans < 0) ans = 0;
printf("%lld\n",ans);
}
return 0;
}