主题链接: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 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
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 ",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 ",ans[0]); } return 0; }
版权声明:本文博客原创文章。博客,未经同意,不得转载。