package qinglin.learn.arithmetic;
public class SackPro_02
{
int p[] =new int[]{9,10,7,4};
int w[] =new int[]{3,5,2,1};
int cp[]=new int[p.length];
int cw[]=new int[w.length];
int x[]=new int[p.length];
int cx[]=new int[p.length];
int currentP,currentW,bestp;
private void printResult()
{
System.out.println("可以装入的最大价值为:"+bestp);
System.out.println("装入的物品依次为:");
for(int i = 0; i < x.length; i++)
{
if(x[i]==1)
System.out.print((i+1)+" ");
}
}
void backtrack(int i)
{
if(i >= 4)
{
if(currentP > bestp)
{
bestp = currentP;
for(int j = 0; j < 4; j++)
x[j] = cx[j];
}
return;
}
if(currentW + w[i] <= 7)
{//搜索右子树
currentW += w[i];
currentP += p[i];
cx[i] = 1;
backtrack(i+1);
currentW -= w[i];
currentP -= p[i];
cx[i] = 0;
}
backtrack(i+1);//搜索左子树
}
public static void main(String[] args)
{
SackPro_02 example = new SackPro_02();
example.backtrack(0);
example.printResult();
}
}
背包问题_最优解法
最新推荐文章于 2023-03-29 09:30:00 发布