Topics Link: http://poj.org/problem?id=3399
Product
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 2837 |
|
Accepted: 686 |
|
Special Judge |
Description
There is a array of N integer numbers in the interval from-30000 to 30000. The task is to a 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) is 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 is in non-increasing order.
Sample Input
4 21720
Sample Output
9 |
Source
Northeastern Europe 2001, Western subregion
Idea: The product of the smallest two negative numbers and the largest two positive numbers is larger each time it is searched.
The code is as follows:
#include <cstdio> #include <algorithm> #include <iostream>using namespace std; #define MAXN 117int 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];//is greater than or equal to zero elsenumf[num2 + +] = a[i];//negative}sort (NUMZ,NUMZ+NUM1); sort (numf,numf+num2); int cont = 0;IF (k&1) {k--;if (num1 > 0) ans[cont++] = Numz[--num1];//k is an odd number. and a positive number. Then there must be at least one positive number in the result else//no greater than or equal to zero, i.e. all negative {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;//is initialized to a number that is less than the given range of 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--)//from large to small output {printf ("%d", Ans[i]);} printf ("%d\n", Ans[0]);} return 0;}
Copyright notice: This article blog original article. Blogs, without consent, may not be reproduced.
POJ 3399 Product (math)