算法设计与分析-贪心算法-最优装载

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

计算机算法与设计

实验内容:贪心算法-最优装载

问题描述:有一批集装箱要装上一艘载重量为c 的轮船。其中集装箱i 的重量为Wi ,最优装载问题要求在装载体积不受限制的情况下,将尽可能多的集装箱装上轮船。

问题分析:

该问题可形式化描述为:

∑=n i i

x 1

max

c x w n i i

i ≤∑=1 {}n i x i ≤≤∈1,1,0

算法描述:最优装载问题可用贪心算法求解。采用重量最轻者先装的贪心选择策略,可产生最优装载问题的最优解。具体算法描述如下:

Template

Void Loading(int x[],Type w[],Type c ,int n)

{

int *t = new int [n+1];

Sort(w,t,n);

for(int i =1;i<+n;i++)

{

x[i] = 0;

}

for (int i = 1;i<=n&&w[t[i]]<=c;i++)

{

x[t[i]] = 1;

c-= w[t[i]];

}

}

所需计算时间为O(nlogn)

运行结果:

另选一组数据输入:

详细设计:

#include

using namespace std;

const int N = 100;

template

void Loading(int x[],Type w[], Type c, int n) {

int *t = new int [n+1];//

Sort(w, t, n); //调用SelectSort函数

for(int k=1; k<=n; k++)

x[k] = 0;//初始化数组x[]

}

for(int i=1; i<=n && w[t[i]]<=c; i++)

{

x[t[i]] = 1; //经判断该集装箱可以装入

c -= w[t[i]]; //轮船可栽重相应减少

}

}

template

void Sort(Type w[],int *t,int n)

{

Type tempArray[N+1],temp;

int min;

memcpy(tempArray,w,(n+1)*sizeof(Type));//将w数组数据拷贝到数组tempArray中

for(int e=1;e<=n;e++)

{

t[e] = e;

for(int i=1;i

min=i;

for(int j=i+1;j<=n;j++)

{

if(tempArray[min]>tempArray[j])

{

min=j;

}

}

Swap(tempArray[i],tempArray[min]);

Swap(t[i],t[min]);

}

}

template

void Swap(Type &x,Type &y) //swap函数

{

Type temp = x;

x = y;

y = temp;

}

int main()

{

float c ; //l轮船总载重

int x[N+1]; //装载结果(0与1分别表示是否装入

int a ;//集装箱数量

cout <<"/////////////贪心算法求解最优装载问题////////////////////"<

cout<<"轮船载重为:";

cin>>c;

cout<<"集装箱数量:";

cin>>a;

float *m = new float [a];

cout<<"待装物品的重量分别为:"<

for(int i = 1;i<=a;i++)

{

cout<<"请输入第"<

cin>>m[i];

}

cout<

cout<<"集装箱列表:"<

for(int j=1; j<=a; j++)

{

cout<

}

cout<

Loading(x,m,c,a);

cout<<"对应的贪心选择结果为:"<

for(int f=1; f<=a; f++)

{ if(x[f]==0||x[f]==1)

cout<

}

cout<

cout<<"集装箱最优装载情况:"<

for(int b=1; b<=a; b++)

{

if (x[b]==0||x[b]==1)

{

if (x[b]==0)

{

cout <<"第"<

}

else

{

cout<<"第"<

}

}

}

cout<<"///////////////////////结束////////////////////////////"<

system("pause");

return 0;

}

相关文档
最新文档