Va 1149: bin packing (Greedy)

Source: Internet
Author: User

Given the weight of N items, the size of the backpack is M. A backpack can hold up to two items. Ask how many backpacks at least.

Idea: greedy, maximum, and minimum. If this is not the case, the greatest one must be lonely for life. Otherwise, the rows are accompanied.

Code:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define N 100100int a[N];int main() {    int t;    scanf("%d", &t);    bool isfirst = true;    while (t--) {        if (isfirst) isfirst = false;        else puts("");        int n;        scanf("%d", &n);        int l;        scanf("%d", &l);        for (int i = 0; i < n; i++) {            scanf("%d", &a[i]);        }        sort(a,a+n);        int st = 0;        int ed = n-1;        int cnt = 0;        while (st <= ed) {            if (st != ed){                if (a[st]+a[ed] <= l) {                    st++;                    ed--;                    cnt++;                } else {                    ed--;                    cnt++;                }            } else {                cnt++;                ed--;            }        }        printf("%d\n", cnt);    }    return 0;}

 

Va 1149: bin packing (Greedy)

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.