This question is on a two-point question list, but what is written based on the binary method will time out on the OJ, according to the prompts given below, we can find that we can use the greedy method to find the best situation to fill each package, so that we can ensure that the number of packages used is the least.
Binary solution:
# Include <iostream> # include <stdio. h >#include <cstring >#include <algorithm> # define Max 100000 using namespace STD; int N, length; int L [Max]; bool CMP (int A, int B) {return a <B;} bool judge (INT mid) {int r = 0, q = 0; int max = 0; int tag [N]; // indicates whether the memset (TAG, 0, sizeof (TAG) has been packaged before. For (INT I = 0; I <n; I ++) {r = length-L [I]; max = I; for (Int J = n-1; j> I; j --) {If (L [J] <R) &&! Tag [J]) {// try to find things that can fill the remaining space max = J; break;} If (! Tag [Max]) {q ++; tag [Max] = 1 ;}}if (q <mid) return false; else return true ;} int main () {int high, low, mid, Res; while (CIN> N) {CIN> length; For (INT I = 0; I <n; I ++) {CIN> L [I];} Sort (L, L + N, CMP); high = N; Low = 0; Res = 0; while (low <= high) {mid = (low + high)/2; If (Judge (MID) {res = mid; Low = Mid + 1;} else high = mid-1 ;} cout <res <Endl;} return 0 ;}
Greedy solution:
#include <iostream>#include <stdio.h>#include <string.h>#include <math.h>#include <algorithm>using namespace std;int li[100003];int ca[100003];bool cmp(int a,int b){ return a>b;}int main(){#ifndef ONLINE_JUDGE freopen("in.txt","r",stdin);#endif int n; int l; while(scanf("%d",&n)!=EOF) { scanf("%d",&l); for(int i=0;i<n;i++) { scanf("%d",&li[i]); ca[i] = l; } sort(li,li+n,cmp); int ans = 0; for(int i=0,j=n-1;i<=j;i++) { if(li[i] + li[j] <= l) { j--; } ans++; } printf("%d\n",ans); } return 0;}