Bin Packing-算是一个复杂度优化的好思想

本文介绍了一种解决Bin Packing问题的贪心策略,通过将物品按长度从大到小排序,尝试将每个物品放入容量不超过l的箱子里。题目要求计算最小的箱子数量。程序实现中使用堆栈,复杂度为O(n),降低了计算复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Bin Packing

My Tags  (Edit)
 Source : SWERC 2005
 Time limit : 1 sec Memory limit : 32 M

Submitted : 412, Accepted : 173

A set of n 1-dimensional items have to be packed in identical bins. All bins have exactly the samelength l and each item i has length l i <= l. We look for a minimal number of bins q such that
  • each bin contains at most 2 items,
  • each item is packed in one of the q bins,
  • the sum of the lengths of the items packed in a bin does not exceed l.

You are requested, given the integer values n, l, l1, ..., ln, to compute the optimal number of bins q.

InputThe first line of the input file contains the number of items n (1 <= n <= 105). The second line containsone integer that corresponds to the bin length l <= 10000. We then have n lines containing one integervalue that represents the length of the items.

There are multiple test cases. Process to end of file.

Output

For each input file, your program has to write the minimal number of bins required to pack all items.

Sample Input

10
80
70
15
30
35
10
80
20
35
10
30

Sample Ouput

6

本题很明显的贪心,以前自己的码量不是很强,所以知道真么弄,也写不出来,把自己想到的能写出来是我做ACM的主要原因。此题很明显是先从大到小的排序,然后从开始往后少找到那个恰好与其和不大于L的放在一起,贪心的正确性很好证明,关键是降低复杂度。实际上很简单,就是与第一个能放到一起的箱子,第二个一定可以和它们放到一起,因此找个堆栈,实际上一个top就行了,在从后往前扫描的过程中不断的入队,下一次的起始点是上一次恰好之和大于L的地方,整体复杂度为:O(n);

#include <iostream>
#include <cstdio>
#include<algorithm>
#include <cstring>
using namespace std;
const int MAX = 100001;
int a[MAX];
int top;

bool cmp(const int &a, const int &b) {
    return a>b;
}

int get_result(int n, int L) {
    sort(a, a + n, cmp);
    top = 0;
    int size = 0;
    for (int i = 0, j = n - 1; i <= j; i++) {
        size++;
        while (a[i] + a[j] <= L && i < j) {
            top++;
            j--;
        }
        if (top > 0) top--;
    }
    size += (top + 1) / 2;
    return size;
}

int main() {
    int n, L;
    while (scanf("%d", &n) != EOF) {
        scanf("%d", &L);
        for (int i = 0; i < n; i++) {
            scanf("%d", &a[i]);
        }
        printf("%d\n", get_result(n, L));
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值