[贪心] UVa1149 Bin Packing 装箱(水题)

题目

给一些垃圾的数目和大小,以及垃圾箱的容量,用最少的垃圾箱子将这些垃圾装进去,注意每个垃圾箱最多只能装两个垃圾。

思路

将重量排序,每次选最大者。
并且能再装一个就装,并且要装剩余容量能装的最大的。
本题用set实现,在效率要求不高的情况下还是蛮方便的。

代码

#include <cstdio>
#include <set>
#include <functional>
using namespace std;

const int maxn = 100000 + 1000;
multiset<int, greater<int> > A; // 特定规则的set 
int n, m;
bool fail = false;

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &m);
        int num;
        for (int i = 0; i<n; i++) {
            scanf("%d", &num);
            A.insert(num);
        }
        int ans = 0;
        while (!A.empty()) {
            int a = *(A.begin());
            A.erase(A.begin());
            ans++;
            if (a>m) {
                fail = true;
                break;
            }
            set<int>::iterator b = A.lower_bound(m - a);
            if (b != A.end()) {
                A.erase(b);
            }
        }
        printf("%d\n", ans);
        if (T) printf("\n");
    }

}

收获

1.把set改成由大到小的:multiset < int, greater< int> > A;
2. 极其方便的lower_bound:当v存在时返回它的第一个位置,如果不存在,返回一个位置,在此处插入v,所有元素往后移动,序列仍有序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值