码迷,mamicode.com
首页 > 其他好文 > 详细

UVa 1149 - Bin Packing

时间:2018-01-20 22:55:05      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:time   return   gpo   std   main   背包   ++   post   style   

链接:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3590

 

题意:

给定N(N≤1e5)个物品的重量Li,背包的容量M,同时要求每个背包最多装两个物品。
求至少要多少个背包才能装下所有的物品。

 

分析:

排序,然后贪心选择即可。如果能和物品A一起装入背包的另一个物品B有多个,则应该选择最重的一个物品B。


证明:
若不是选择物品B,而是选择物品C(C的重量小于B),则总的背包数不仅没有减少,反而可能增加。

 

代码:

 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 int a[100000+5];
 6 
 7 int main(){
 8     int T, n, b;
 9     scanf("%d", &T);
10     while(T--){
11         scanf("%d%d", &n, &b);
12         for(int i = 0; i < n; i++) scanf("%d", &a[i]);
13         sort(a, a + n);
14 
15         int remain = n;
16         for(int L = 0, R = n - 1; L < R; R--){
17             if(a[L] + a[R] <= b) L++, remain -= 2;
18         }
19         printf("%d\n", (n + remain) / 2);
20         if(T) printf("\n");
21     }
22     return 0;
23 }

 

UVa 1149 - Bin Packing

标签:time   return   gpo   std   main   背包   ++   post   style   

原文地址:https://www.cnblogs.com/hkxy125/p/8321959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!