[贪心] 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,所有元素往后移动,序列仍有序。

猜你喜欢

转载自blog.csdn.net/icecab/article/details/80532077
今日推荐