您的位置:首页 > 运维架构

TopCoder SRM 598 Div1 第1题

2013-12-02 20:20 387 查看
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.

The capacity of each bin is 300. She can put an arbitrary number of items into a single bin, but the total weight of items in a bin must be less than or equal to 300.

You are given the vector <int> item. It is known that the weight of each item is between 100 and 300, inclusive. Return the minimal number of bins required to store all items.

Definition

 

Class:

BinPacking

Method:

minBins

Parameters:

vector <int>

Returns:

int

Method signature:

int minBins(vector <int> item)

(be sure your method is public)

 

 

Constraints

-

item will contain between 1 and 50 elements, inclusive.

-

Each element of item will be between 100 and 300, inclusive.

Examples

0)

 

 

{150, 150, 150, 150, 150}

Returns: 3

You have five items and each bin can hold at most two of them. You need at least three bins.

1)

 

 

{130, 140, 150, 160}

Returns: 2

For example, you can distribute the items in the following way:

Bin 1: 130, 150
Bin 2: 140, 160
2)

 

 

{100, 100, 100, 100, 100, 100, 100, 100, 100}

Returns: 3

 

3)

 

 

{100, 200, 100, 100, 100, 100, 200, 100, 200}

Returns: 4

 

4)

 

 

{157, 142, 167, 133, 135, 157, 143, 160, 141, 123, 162, 159, 165, 137, 138, 152}

Returns: 8

 

类型:其他  难度: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;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  TopCoder C++