码迷,mamicode.com
首页 > 其他好文 > 详细

PKU3399贪心

时间:2014-08-04 18:03:37      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   color   os   strong   io   for   

原题http://poj.org/problem?id=3399

Product
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 2839   Accepted: 688   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
//第一次写的时候想分类讨论,发现这是一个很复杂的问题,需要考虑的问题有很多
//第二次的时候想到了用找的方法。但是比赛的时候感觉到有点麻烦。所以就没写。。。现在想想,挺后悔的。
//本题的思路是先按绝对值进行排序。然后进行查询。如果说碰到了负的先记录。如果碰到正的,就放入

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <limits.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <stack>
#include <queue>
#include <deque>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define N 100 + 10

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;
	int i;
	int num[N],ans[N],f[5];

	while(~scanf("%d%d",&n,&k)){
		memset(num,0,sizeof(num));
		memset(ans,0,sizeof(ans));
		memset(f,0,sizeof(f));
		for(i=0;i<n;i++){
			scanf("%d",&num[i]);
		}
		sort(num,num+n,cmp);
		int l = 0;
		int flag = 0;
		for(i=n-1;i>=0&&l<k;i--){
			if(num[i]<0 && flag==0){
				f[0] = num[i];
				flag = 1;
			}
			else if(num[i]<0 && flag==1 && l+2<=k){//如果放的下就直接放下
				ans[l++] = f[0];
				ans[l++] = num[i];
				flag = 0;
			}
			else if(num[i]<0 && flag==1 && l+2>k){//如果不够了,那就就要进行判断。选择最优解
				int j,x;
				for(j=i-1;j>=0;j--){
					if(num[j] >= 0){
						break;
					}
				}
				for(x=l-1;x>=0;x--){
					if(ans[x] >= 0){//楼了个等于。。。。
						break;
					}
				}
				if(x>=0 && j>=0){
					if(num[j]*ans[x] >= f[0]*num[i]){
						ans[l++] = num[j];
					}
					else{
						ans[l++] = num[i];
						ans[x] = f[0];
					}
				}
				flag = 0;
			}
			else if(num[i] > 0){
				ans[l++] = num[i];
			}
		}
		if(l < k){//如果案例为5 5 3 2 1 0 0 
			for(i=0;i<k;i++){
				ans[i] = num[i];
			}
		}
		sort(ans,ans+k);
		for(i=k-1;i>=0;i--){
			if(i != 0){
				printf("%d ",ans[i]);
			}
			else{
				printf("%d\n",ans[i]);
			}
		}
	}

	return 0;
}


 

PKU3399贪心,布布扣,bubuko.com

PKU3399贪心

标签:des   style   http   color   os   strong   io   for   

原文地址:http://blog.csdn.net/zcr_7/article/details/38369171

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!