Problem Statement | |||||||||||||
| Fox Ciel has some items. The weight of the i-th (0-based) item is item[i]. She wants to put all items into bins. | ||||||||||||
Definition | |||||||||||||
|
| ||||||||||||
| |||||||||||||
| |||||||||||||
Constraints | |||||||||||||
- | item will contain between 1 and 50 elements, inclusive. | ||||||||||||
- | Each element of item will be between 100 and 300, inclusive. | ||||||||||||
Examples | |||||||||||||
0) |
| ||||||||||||
|
| ||||||||||||
1) |
| ||||||||||||
|
| ||||||||||||
2) |
| ||||||||||||
|
| ||||||||||||
3) |
| ||||||||||||
|
| ||||||||||||
4) |
| ||||||||||||
|
|
类型:其他 难度:2.5
题意:给出一组数,表示一组物品的重量,每个物品重量范围[100,300],现在要将这组物品放到若干个桶中,每个桶最多放重量300的物品,问最少需要多少桶
分析:一开始把题目想简单了,经过几次修改才正确。
1、首先将物品按重量排序,从重量大的遍历,考虑大于200的物品,这些物品必定一个物品占一个桶(因为最轻的物品重量为100,大于200的不能和其他物品放在一个桶里)
2、再遍历剩余的物品,找到当前最重的物品,并找到能和它放在一个桶中的最重的物品
(1)若没有和它能放在一个桶中的,那么这个物品单独占一个桶
(2)若有,那么这两个物品放在一个桶中
3、若当前最重物品重量为100,那么还需要(剩余物品数+2)/ 3 个桶
代码:
#include<string>
#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
using namespace std;
class BinPacking
{
public:
int minBins(vector <int> item)
{
sort(item.begin(),item.end());
int ans = 0;
vector<int>::iterator it;
while(!item.empty() && item.back()>200)
{
ans++;
item.pop_back();
}
while(!item.empty())
{
int i=item.size()-1,j=i-1;
if(item[i]==100)
{
ans += (item.size()+2)/3;
return ans;
}
for(; j>=0; j--)
{
if(item[i]+item[j]<=300)
break;
}
item.pop_back();
if(j>=0) item.erase(item.begin()+j,item.begin()+j+1);
ans++;
}
return ans;
}
};
int main()
{
int a[] = {100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 193, 160, 124, 178, 105, 150, 140, 117, 219, 126, 153, 183, 212, 179, 140, 103, 195};
vector<int> tmp;
for(int i=0; a[i]>0; i++)
{
tmp.push_back(a[i]);
}
BinPacking t;
cout<<t.minBins(tmp)<<endl;
}