首页 > 其他 > 详细

poj 3399 Product(数学题)

时间:2014-08-04 11:03:07      阅读:237      评论:0      收藏:0      [点我收藏+]

题目链接:http://poj.org/problem?id=3399


Product
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2837   Accepted: 686   Special Judge

Description

There is an array of N integer numbers in the interval from -30000 to 30000. The task is to select K elements of this array with maximal possible product.

Input

The input consists of + 1 lines. The first line contains N and K (1 ≤ K ≤ N ≤ 100) separated by one or several spaces. The others contain values of array elements.

Output

The output contains a single line with values of selected elements separated by one space. These values must be in non-increasing order.

Sample Input

4 2
1
7
2
0

Sample Output

7 2

Source

Northeastern Europe 2001, Western Subregion

思路:每次寻找最小的两个负数和最大的两个正数的乘积中较大的;


代码如下:

#include <cstdio>
#include <algorithm>
#include <iostream>
using namespace std;
#define MAXN 117
int main()
{
	int n, k;
	int a[MAXN], numz[MAXN], numf[MAXN];
	int ans[MAXN];
	int i, j;
	int num1, num2;
	while(~scanf("%d %d",&n,&k))
	{
		num1 = num2 = 0;
		for(i = 0; i < n; i++)
		{
			scanf("%d",&a[i]);
			if(a[i] >= 0)
				numz[num1++] = a[i];//大于等于零
			else
				numf[num2++] = a[i];//负数
		}
		sort(numz,numz+num1);
		sort(numf,numf+num2);
		int cont = 0;
		if(k&1)
		{
			k--;
			if(num1 > 0)
				ans[cont++] = numz[--num1];//k为奇数,且有正数,那么结果中必然会有至少一个正数
			else//没有大于等于零的数,即全为负数
			{
				for(i = num2-1; i > num2-k-1; i--)
				{
					printf("%d ",numf[i]);
				}
				printf("%d\n",numf[num2-k-1]);
				continue;
			}
		}
		j = 0;
		for(i = 0; i < k/2; i++)
		{
			int t1 = -4017;//初始化为一个小于给定范围的数字
			int t2 = -4017;
			if(num1 == 1 && num2-j == 1)
			{
				ans[cont++] = numz[--num1];
				ans[cont++] = numf[++j];
			}
			else
			{
				if(num1 > 1)
					t1 = numz[num1-1]*numz[num1-2];
				if(num2-j > 1)
					t2 = numf[j] * numf[j+1];
				if(t1 > t2)
				{
					ans[cont++] = numz[--num1];
					ans[cont++] = numz[--num1];
				}
				else
				{
					ans[cont++] = numf[j++];
					ans[cont++] = numf[j++];
				}
			}
		}
		sort(ans,ans+cont);
		for(i = cont-1; i > 0; i--)//从大到小输出
		{
			printf("%d ",ans[i]);
		}
		printf("%d\n",ans[0]);
	}
	return 0;
}



poj 3399 Product(数学题),布布扣,bubuko.com

poj 3399 Product(数学题)

原文:http://blog.csdn.net/u012860063/article/details/38365719

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!