HDU-5504(逻辑if-else大水题)

本文详细解析了一个关于从一组整数中寻找最大乘积的问题,包括处理特殊情况如0和负数的方法,通过示例说明了如何正确实现算法。
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
 

思路:
这题恶心我了一晚上,昨天实在是没做的出来,今天缓了一天,然后给A了
题目大意是让你找出所给的一串数字中能达到的最大乘积,有很多的细节需要考虑
关键是要想到0,想清楚哪几种情况会受到0存在的影响
只要有正数存在,不管负数和0存在与否,都不会影响按照“一般流程”下来的最后结果
正数不存在,那么又有两种小的分支:负数也不存在和负数存在个数的问题
(1)只有一个负数,这个时候还要考虑有没有0!!!
(2)没有负数,只有0,那结果就是0.
是的,只有这两种情况会受到0存在的影响,要单独拿出来处理,其他的情况走大流程就OK

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

int main()
{
    int T;
    __int64 t;
    scanf("%d",&T);
    while(T--)
    {
        __int64 ans = 1;
        __int64 a[65];
        int n;
        int q = 0,f = 0; 
        scanf("%d",&n);
        for(int i = 1;i <= n;i++) {
            scanf("%I64d",&t);
            if(t > 0) ans *= t;
            else if(t == 0) f++;
            else a[++q] = t;
        }
        //把0会造成影响的两种特殊情况拿出来处理一下 
        if(q+f == n) {
            if(!q) {
                printf("0\n");
                continue;
            }
            if(q == 1) {
                if(!f) {printf("%I64d\n",a[1]);continue;}
                if(f) {printf("0\n");continue;}
            }
        }
        //如果有正数存在 
        if(q%2 == 0) {
            for(int i = 1;i <= q;i++)
                ans *= a[i];
            printf("%I64d\n",ans);
            continue;
        }
        else {
            sort(a+1,a+1+q);
            for(int i = 1;i <= q-1;i++)
                ans *= a[i];
            printf("%I64d\n",ans);
            continue;
        }
    }
)   return 0;
}

 

转载于:https://www.cnblogs.com/immortal-worm/p/4959269.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值