给定一艘容量为C的船,给定一批货物,货物i的重量是wi,要求在船不超重的前提下,将尽可能多的货物装上船。
//回溯法
#include<stdio.h>
int n,c; //货物的个数 和 船的容积
int cw; //已装总重量
int bestw; //最优解
int *w;
void backtrack(int i)
{
if (i==n+1)
{
if(bestw<cw)
bestw=cw;
return;
}
if(cw+w[i-1]<=c)
{
cw+=w[i-1];
backtrack(i+1);
cw=cw-w[i-1];
}
backtrack(i+1);
}
void main ()
{
int i;
printf("input the number of boxes and the volume of the ship:");
scanf("%d%d",&n,&c);
w=new int[n];
printf("input the weights of each box:");
for(i=0;i<n;i++)
scanf("%d",w+i);
backtrack(0);
printf("the result is %d.\n",bestw);
}