Bin Packing-算是一个复杂度优化的好思想
2012-07-08 13:55
218 查看
Bin Packing
My Tags | (Edit) |
---|
Source : SWERC 2005 | |||
Time limit : 1 sec | Memory limit : 32 M |
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 li <= 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; }
相关文章推荐
- 最近正在开发的一个项目,将它的进展写出来,也算是一种老调长谈的再次思想回顾吧
- 一个跨库复杂查询的SQL优化的案例
- 79、tensorflow计算一个五层神经网络的正则化损失系数、防止网络过拟合、正则化的思想就是在损失函数中加入刻画模型复杂程度的指标
- 58.java编程思想——创建窗口和程序片 一个复杂的Bean
- 79、tensorflow计算一个五层神经网络的正则化损失系数、防止网络过拟合、正则化的思想就是在损失函数中加入刻画模型复杂程度的指标
- 一个文本文件,大约有一万行,每行一个词,要求统计出其中最频繁出现的前10个词,请给出思想,给出时间复杂度分析
- hive 优化遇到的一个问题:hive.auto.convert.join
- 一个连通图,采用邻接表作为存储结构,设计一个算法从顶点v出发的深度优化遍历的非递归过程
- 查询优化:说说一个数据库的查询方法
- 收集几篇软件测试职业规划的文章,算是给自己一个灯塔
- 一个C#代码优化的案例
- 借鉴系统UITableView的设计思想,自定义一个"花瓣"菜单
- 写一个函数判断单链表是否存在环,要求时间复杂度为O(n)
- 一个便于优化的网站应该具有哪些细节
- 一个模式匹配算法的优化
- 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序
- 3.使用cvPyrDown()缩放图像(一个复杂一点的变换)
- 一个SQL查询优化
- 已知一个整数数组A[n],写出算法实现将奇数元素放在数组的左边,将偶数放在数组的右边。要求时间复杂度为O(n)。
- 仿基因编程原理导论(里面的几个重要的概念正在做修正,所以这只能算是一个原理的初稿。)