关于装载问题的C++

来源:百度知道 编辑:UC知道 时间:2024/05/17 04:12:39
除了MAIN函数以外,其余都是标准的代码
因为不知道怎么用main将其连接起来
貌似在main中调用maxloading有误

问题简单描述:现有一首轮船重量C,n个box,所有box的重量>c,要求将尽可能多的box装入轮船上(运用的是算法设计中的回溯法),求出最优装在办法和记录下路径

类loading中,n为box数量,*x为当前解,*bestx为当前最优解,*w为box重量数组,c为轮船重量,,cw为当前载重量,bestw为当前最有载重量,r为剩余box重量(即选择一个box放入轮船,余下所有没有放入轮船的box的重量)

Maxloading函数为返回最有装载重量(可以不等于C,只要无限接近)

#include <conio.h>
#include <iomanip.h>
#include <iostream.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template<class Type>
class Loading{

friend Type MaxLoasing(Type[],Type,int,int[])

private:
voidBacktrack(int i);
int n,*x,*bestx;
Type*w,c,cw,bestw,r;

};

template<class Type>
void Loading<Type>::Backtrack(int i){

if(i>n-1){
if(cw>bestw){for(j=0;j<=n-1;j++)
{
bestx[j]=x[j];
bestw=cw;

将MaxLoading(*w,c,n,*bestx); 修改为:
MaxLoading(w,c,n,bestx);
就可以了

另外,你这个程序估计你敲错的太多了
我修改后,可以编译过,也许有其他逻辑错误:
#include <conio.h>
#include <iomanip.h>
#include <iostream.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

template<class Type>
class Loading
{
friend Type MaxLoading(Type[],Type,int,int[]);
private:
void Backtrack(int i);
int n,*x,*bestx;
Type*w,c,cw,bestw,r;
};

template<class Type>
void Loading<Type>::Backtrack(int i)
{
if(i>n-1)
{
if(cw>bestw)
{
for(int j=0;j<=n-1;j++)
{
bestx[j]=x[j];
bestw=cw;
}
return;
}

r-=w[i];
if(cw+w[i]<=c)
{
x[i]=1;
cw+=w[i];
Backtrack(i+1);
cw-=w[i];
}

if(cw+r>bestw)
{ <