UVA 1149 Bin Packing 装箱(贪心)

每次选最大的物品和最小的物品放一起,如果放不下,大物体孤独终生,否则相伴而行。。。

答案变得更优是因为两个物品一起放了,最大的物品是最难匹配的,如果和最小的都放不下的话,和其它匹配也一定放不下了。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+42;
int a[maxn];

template<class T>
inline void scan_d(T *ret)
{
    char c;*ret=0;
    while((c=getchar())<'0'||c>'9');
    while(c>='0'&&c<='9') { *ret = *ret*10+(c-'0'); c = getchar();}
}

int main()
{
    int T;  scan_d(&T);
    while(T--){
        int n,L; scan_d(&n); scan_d(&L);
        for(int i = 0; i < n; i++) scan_d(a+i);
        sort(a,a+n);
        int i = 0,j = n-1;
        int ans = n;

        while(i<j){
            if(a[i] <= L-a[j]){
               i++; j--; ans--;
            } else {
                j--;
        }

        printf("%d
",ans);
        if(T)putchar('
');
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jerryRey/p/4695359.html