- 设有n个货物要装入若干个容量为C的集装箱以便运输,这n个货物的体积分别是{S1, S2, …, Sn},且有si<C(1≤i≤n)。为节省运输成本,用尽可能少的集装箱为装运这n个货物。分别采用以下两种贪心策略对其进行求解:
- 最先适宜策略(firstfit):首先将所有的集装箱初始化为空,对于所有货物,按照所给的次序,每次将一个货物装入第一个能容纳它的集装箱中;
- 最优适宜策略(bestfit):总是把货物装到能容纳它,且目前剩余容量最小的集装箱中,使得该箱子装入货物后闲置空间最小。
分别实现上述两个策略。
提示:
- 输入n个货品的体积,以及每个集装箱的大小C
- 输出两种策略下需要的集装箱个数
对最先适宜策略,每次放新货物,从已装的箱子中依次搜索能容纳货物的箱子,找到合适的立马装上并进行下一个货物的装放;对最优适宜策略,每次放新货,都要对所有已装的箱子进行试装,找出装入货物后,剩余容量最小的箱子,并把货物装入。
代码:
#include<iostream>
using namespace std;
#define M 100
int Get_firstfit(int num,int a[],int size){ //最先适宜策略
int box[M]; //定义足够大的集装箱数组
int count=0;//集装箱个数
int i,j;
for(i=0;i<num;i++)
{
box[i]=0; //0表示第i+1个集装箱未装任何货物,
}
for(i=0;i<num;i++)
{
j=0;
while(size-box[j]<a[i]) //第i+1个集装箱剩余容量与下一个货物体积进行比较
{ //集装箱剩余空间小于下一个货物体积则选择下一个集装箱进行装载货物
j++;
}
box[j]=box[j]+a[i]; //集装箱当剩余前容量+装入货物体积
count=count>(j+1)?count:(j+1);
}
return count; //返回集装箱个数
}
int Get_bestfit(int num,int a[],int size) //最优适宜策略
{
int box[M]; //定义足够大的集装箱数组
int count=0;//集装箱个数
int i,j,min,m,temp;
for(i=0;i<num;i++)
{
box[i]=0; //0表示第i+1个集装箱未装任何货物,
}
for (i=0;i<num;i++)
{
min=size;
m=count+1;
for(j=0;j< count+1;j++)
{
temp=size-box[j]-a[i]; //当前空间=集装箱容量-集装箱已存入量-载入货物体积
if(temp>0&&temp< min)
{
min=temp;
m=j;
}
}
box[m]=box[m]+a[i]; //集装箱当剩余前容量+装入货物体积
count=count>(m+1)?count:(m+1);
}
return count;
}
int main(){
int num,size;//num为货物个数,size为每个集装箱容量大小
int a[100]; //定义一个长度为100的数组
cout<<"Enter the number of the goods:"<<endl;
cin>>num;
cout<<"Enter the size of "<<num<<" goods:"<<endl;
for(int i=0;i<num;i++)
{
cin>>a[i];
}
cout<<"Enter the size of each container:"<<endl;
cin>>size;
cout<<"the number of container with firstfit strategy is:"<<Get_firstfit(num,a,size)<<endl;
cout<<"the number of container with bestfit strategy is:"<<Get_bestfit(num,a,size)<<endl;
return 0;
}
运行截图: