Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 2813 | Accepted: 672 | 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 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个数字,乘起来. 找哪几个数字乘积最大.
我是用贪心的思想.
从绝对值最大的开始找. 如果是负数,就要成对成对加到ans数组里.
当ans只能放入一个数的时候, 要判断下, 具体的看代码里的备注吧.
如果 最后找不到 k数字相乘能大于等于0 的话, 就把前n个绝对值最小的数 输出就行了. 因为肯定是负数或者小于零了,所以要让product尽可能地小.
#include<stdio.h>
#include<algorithm>
using namespace std;
int abb(int a)
{
if(a<0)
return -a;
else
return a;
}
int cmp(int a,int b)
{
return abb(a)<abb(b);
}
int main()
{
int n,k,i,j,flag;
int a[200],z[200],f[200],tem,ttt[5],ans[200],l,x;
while(scanf("%d%d",&n,&k)!=EOF)
{
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
l=0;
sort(a,a+n,cmp);
flag=0;
for(i=n-1;i>=0&&l<k;i--)//提取出k个数,负数都是成对出来的,最后成绩肯定是负数.
{
if(a[i]<0&&flag==0)//flag 代表缓存区ttt里有几个负数
{
ttt[0]=a[i];
flag=1;
}
else if(a[i]<0&&flag==1&&l+2<=k)//一次入两个 可能超出k 范围 ,所以用l+2<=k限制
{
ans[l++]=ttt[0];
ans[l++]=a[i];
flag=0;
}
else if(a[i]<0&&flag==1&&l+2>k) //l+2>k 如果加入两个负数后,数字个数超过k, 就是说多了一个
{
for(j=i-1;j>=0;j--)//在剩下的输入的数里面 找到一个最大的正数
{
if(a[j]>=0)
break;
}
for(x=l-1;x>=0;x--)//在挑出来的ans数组里面 找到一个最小的正数
{
if(ans[x]>=0)
break;
}
if(j>=0&&x>=0)//找到了这两个正数
{
if(a[j]*ans[x]<ttt[0]*a[i])//判断新找到的两个负数乘积大,还是那两个正数成绩大.大的进入ans数组
{
ans[l++]=ttt[0];
ans[x]=a[i];
}
else
{
ans[l++]=a[j];
}
}
flag=0;
}
else if(a[i]>=0)
ans[l++]=a[i];
}
if(l<k)//代表任意k个数的成绩 无法形成正数或者零, 就取绝对值最小的前k个数
{
for(i=0;i<k;i++)
{
ans[i]=a[i];
}
}
sort(ans,ans+k);
for(i=k-1;i>=0;i--)
{
if(i==k-1)
printf("%d",ans[i]);
else
printf(" %d",ans[i]);
}
puts("");
}
return 0;
}