hdu5504 GT and sequence

本文介绍了一种算法问题——如何从一组整数中选择若干个数(至少一个),使这些数的乘积最大。通过分析正数、负数及零的数量来确定最优解,并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 2^63−1.

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.

1≤T≤1000
1≤N≤62

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
BestCoder Round #60

题意:给出一串数(1≤N≤62) ,问从中取出一系列的数(至少一个),,使得这些数的乘积最大。
解法:首先找出给出的串中正数与负数。。以及0的个数。
1:当这一串数只有一个时,无论这个数是正负还是0都要取这个数。
2:当没有正数时,剩下的负数所组成的最大数(见3),若有0,则为0,没有这个这个做大数。
3:负数组成的最大数,,当负数个数为奇数时,取偶数个且最大那个不取,当为偶数数,全取。
4:结果为负数组成的最大数乘所有正数。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
    int T_T;
    int n;
   // int a[100];
    long long fu[100];
    long long zheng[100];
    int pp,qq,cnt;
    long long out,w;
    scanf("%d",&T_T);
    while(T_T--)
    {
        pp=0;//zheng
        qq=0; //fu
        cnt=0; //0
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%I64d",&w);
            if(w>0) zheng[pp++]=w;
            else if(w<0) fu[qq++]=w;
            else cnt++;
        }
        sort(fu,fu+qq);
        if(pp==0&&qq==0&&cnt!=0) out=0;
        else if(pp==0&&qq==1&&cnt==0) out=fu[0];
        else if(pp==1&&qq==0&&cnt==0) out=zheng[0];
        else if(pp==0&&qq==1&&cnt!=0) out=0;
        else
        {
            out=1;
            for(int i=0;i<pp;i++) out=out*zheng[i];
            if(qq%2==0)
            {
                for(int i=0;i<qq;i++) out=out*fu[i];
            }
            else
            {
                for(int i=0;i<qq-1;i++) out=out*fu[i];
            }
        }
        printf("%I64d\n",out);
    }
    return 0;
}
/*********
考虑只有一个数,和有0的情况
最大就是:最大偶数个负数*所有正数
*********/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值