/*Product
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 N + 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*/
//在n个数中,找出k个数使得他们的乘积最大。并按从大到小输出这k个数。
思路:先排序,找出最大正数的积,负数的最大乘积,然后比较
#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];//大于等于零 ,即numz数组存放的是非负数
else
numf[num2++] = a[i];//负数 ,即numf数组存放的是负数
}
sort(numz,numz+num1);
sort(numf,numf+num2);
int cont = 0;
if(k%2==1)
{
k--;
if(num1 > 0)
ans[cont++] = numz[--num1];//k为奇数,且有正数,那么结果中必然会有至少一个正数
else//没有大于等于零的数,即全为负数
{
for(i = num2-1; i >=num2-k-1; i--)
{
printf("%d ",numf[i]);//输出最后k个数,即负数中最大的那k个数
}
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];
} //比较t1和t2的值
else
{
ans[cont++] = numf[j++];
ans[cont++] = numf[j++];
}
}
}
sort(ans,ans+cont);
for(i = cont-1; i >= 0; i--)//从大到小输出
{
printf("%d ",ans[i]);
}
}
return 0;
}