给定有n个物体,用数组表示各个物体的大小,箱子容量为capacity,最少用多少个箱子把这n个物体装下
方法1:
#include <iostream>
using namespace std;
int minContainer(int len, int capacity, int arr[]) {
struct BNode
{
int remain;
BNode* next;
};
BNode* pHead = nullptr;
BNode* pNode = nullptr;
BNode* pTail = nullptr;
for (int i = 0; i < len; ++i) {
pNode = pHead; //每次从头开始
while (pNode != nullptr && pNode->remain < arr[i])
pNode = pNode->next;
if (pNode == nullptr) {
//需要开新箱子
pNode = new BNode();
pNode->remain = capacity;
pNode->next = nullptr;
if (!pHead) {
//头节点为空,设置头节点
pHead = pTail = pNode;
}
else{
pTail->next = pNode; //旧箱子的最后一个箱子指向新箱子
pTail = pNode; //更新pTail指向最后一个箱子
}
}
pNode->remain -= arr[i];
}
//统计箱子数
int boxNum = 0;
pNode = pHead;
while (pNode != nullptr) {
boxNum++;
pNode = pNode->next;
}
return boxNum;
}
int main() {
//int arr[5] = { 4, 8, 6, 7, 8 }; //boxNum = 4
int arr[9] = { 6, 5, 2, 1, 7, 4, 9, 10 }; //boxNum = 5
sort(arr, arr + 9,
[] (int a, int b)
{return a > b;}); //降序排列
cout << minContainer(9, 12, arr) << endl;
system("pause");
}
方法2:
#include <iostream>
#include <list>
using namespace std;
int minContainer(int len, int capacity, int arr[]) {
list<int> ilst;
//ilst.push_back(capacity);
list<int>::iterator lst_it; //= ilst.begin();
for(int i = 0; i < len; ++i){
lst_it = ilst.begin(); //每次从头开始
while(*lst_it < arr[i])//查找刚好能放下arr[i]的箱子
++lst_it;
//当前箱子都放不下arr[i]
if(lst_it == ilst.end()){
ilst.push_back(capacity);
--lst_it;//lst_it指向新加入的箱子
}
*lst_it -= arr[i];
}
return ilst.size();
}
bool compare(int a, int b)
{return a > b;}
int main() {
//int arr[5] = { 4, 8, 6, 7, 8 }; //boxNum = 4
int arr[9] = { 6, 5, 2, 1, 7, 4, 9, 10, 4}; //boxNum = 5
//int arr[7] = {2, 5, 4, 7, 1, 3, 8};//boxNum = 3
sort(arr, arr + 9, compare); //降序排列
cout << minContainer(9, 12, arr) << endl;
system("pause");
}