且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

hdu 5504 GT and sequence【BestCoder Round #60 】

更新时间:2021-09-12 23:14:43

GT and sequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1441    Accepted Submission(s): 336


Problem Description
You are given a sequence of N integers.

You should choose some numbers(at least one),and make the product of them as big as possible.

It guaranteed that **the absolute value of** any product of the numbers you choose in the initial sequence will not bigger than 2631.
 

Input
In the first line there is a number T (test numbers).

For each test,in the first line there is a number N,and in the next line there are N numbers.

1T1000
1N62

You'd better print the enter in the last line when you hack others.

You'd better not print space in the last of each line when you hack others.
 

Output
For each test case,output the answer.
 

Sample Input

1 3 1 2 3
 

Sample Output

6
 

Source


题目大意:

给出NN个整数。你要选择至少一个数,使得你选的数的乘积最大。
保证任意选一些数相乘的绝对值都不会大于2^{63}-12631
官方题解:

注意先特判00的情况:如果读入的数据有00,那么去掉所有的00且最后答案和00取一个max。

剩下的正数显然全部乘起来比较优。

对于负数的话,如果个数是奇数个我们就去掉绝对值最小的那一个,然后全部乘起来即可。

我的思路:

其实跟官方的题解是差不多的,但是我的想法就是分别找到 0 和 负数 的个数,然后特判 当 n == 1 的时候就直接输出,

当 0 的个数 是 n 或者是 n-1 && 负数的个数是 1 的时候, 输出0

剩下的就是判断当负数的个数是奇数还是偶数,最后输出结果就行了。。。

上代码:(还是比较水的)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
const int maxn = 1e2+5;
const double eps = 1e-7;

LL arr[maxn], a[maxn];
int main()
{
    int T, n;
    cin>>T;
    while(T--)
    {
        cin>>n;
        LL ret = 1, cnt = 0, ans = 0;
        for(int i=0; i<n; i++)
        {
            cin>>arr[i];
            if(arr[i] > 0)
                ret *= arr[i];
            else if(arr[i] < 0)
                a[cnt++] = -arr[i];
            else
                ans++;
        }
        sort(a, a+cnt);
        if(n == 1)
            cout<<arr[0]<<endl;
        else if((ans==n-1&&cnt==1) || (ans==n))
        {
            ///cout<<ans<<" "<<cnt<<endl;
            puts("0");
        }
        else
        {
            if(cnt&1)
                for(int i=1; i<cnt; i++)
                    ret *= a[i];
            else
                for(int i=0; i<cnt; i++)
                    ret *= a[i];
            cout<<ret<<endl;
        }
    }
    return 0;
}