GT and sequence

本文介绍了一个编程问题,即如何从一组整数中选取若干个数(至少一个),以使这些数的乘积最大。文章提供了详细的解题思路及C++实现代码。

题目:

GT and sequence

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


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
 
题意:
在给定的数字中挑选一些数,使得乘积最大。
思路:
只要是正数肯定要选择,在选择偶数个负数,从小到大进行选择。特殊情况:全部数字都为小于等于0的数,那就把序列中最大的数输出,因为题目要求至少选择一个数。
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

int main(int argc, char const *argv[]) {
	freopen("in.txt", "r", stdin);
	int T;
	scanf("%d", &T);
	while (T--) {
		int n, nesum = 0, flag = 0, c = 1;
		__int64 a[70], b[70], pro = 1;
		scanf("%d", &n);
		for (int i = 1; i <= n; i++) {
			scanf("%I64d", &a[i]);
			if (a[i] < 0) {
				nesum++;
				b[nesum] = a[i];
			} else if (a[i] > 0) {
				pro *= a[i];
				flag = 1;
			} else
				c = a[i];
		}
		sort(a + 1, a + n + 1);
		sort(b + 1, b + nesum + 1);
		int t = nesum / 2 * 2;
		for (int j = 1; j <= t; j++) {
			pro *= b[j];
			flag = 1;
		}
		__int64 ans;
		if (flag)
			ans = pro;
		else
			ans = pro * a[n];
		printf("%I64d\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值