0-1背包:给定n种物品和一背包。物品i的重量是wi,其价值为vi,背包的容量为C。问应如何选择装入背包的物品,使得在总重量不超过背包的容量C的前提下装入背包中物品的总价值最大。
package 实验五;
import java.util.Scanner;
public class 背包问题 {
public static void main(String[] args) {
Bag b=new Bag();
b.Set();
b.Input();
b.Backtrack(0);
b.Output();
}
}
class Bag{
int c; //背包容量
int n; //物品数量
int [] w; //各物品重量
int [] p; //各物品价值
int [] x; //解向量
int cw; //当前重量
int cv; //当前价值
int bestv; //当前最优价值
int [] bestx; //当前最优价值对应的解
Bag(){
n=0;
cw=cv=bestv=0;
}
void Set(){
System.out.println("请输入物品数量:");
Scanner reader=new Scanner(System.in);
n=reader.nextInt();
this.n=n;
x=new int[n];
p=new int[n];
w=new int[n];
bestx=new int[n];
}
void Input()
{
int i;
Scanner reader=new Scanner(System.in);
System.out.println("请输入背包容量:");
c=reader.nextInt();
System.out.println("请输入各物品重量:");
for (i=0; i<n; i++)
w[i]=reader.nextInt();
System.out.println("请输入各物品价值:");
for (i=0; i<n; i++)
p[i]=reader.nextInt();
}
void Output(){
int i;
for (i=0;i<n; i++)
System.out.print(bestx[i]+" ");
System.out.println();
}
void Backtrack(int t)
{
if (t>n-1)
{
if (cv>bestv)
{
bestv=cv;
for (int i=0; i<n; i++)
bestx[i]=x[i];
}
}
else
{
for (int i=0; i<=1; i++)
{
x[t]=i;
if (i==0)
Backtrack(t+1);
else
if(cw+w[t]<=c)
{
cw=cw+w[t];
cv=cv+p[t];
Backtrack(t+1);
cw=cw-w[t];
cv=cv-p[t];
}
}
}
}
}
请输入物品数量:
3
请输入背包容量:
30
请输入各物品重量:
16 15 15
请输入各物品价值:
45 25 25
0 1 1