[Hoj] 2160 bin packing binary, greedy

Source: Internet
Author: User

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;}


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.