2.写出一般背包问题的贪心算法。
输入:先输入物品的个数n,再输入背包的容量c,然后依次输入物品的重量wi,最后依次输入物品的价值vi。注意:所有值都不能随机生成!!!
输出:物品的选择向量xi,0=
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int c=scan.nextInt();
double w[]=new double [n];
double v[]=new double [n];
double index[]=new double [n];
double x[]=new double [n];
for (int i = 0; i < n; i++) {
w[i]=scan.nextInt();
}
for (int i = 0; i < n; i++) {
v[i]=scan.nextInt();
}
for (int i = 0; i < n; i++) {
index[i]=i;
}
aaa(w, v, index, x, n, c);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (index[j]==i) {
System.out.print(x[j]+" ");
}
}
}
}
public static void aaa(double w[],double v[],double index[],double x[],int n,double c)
{
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (v[i]/w[i]<v[j]/w[j]) {
double m=w[i];
w[i]=w[j];
w[j]=m;
m=v[i];
v[i]=v[j];
v[j]=m;
m=index[i];
index[i]=index[j];
index[j]=m;
}
}
}
int i;
for ( i = 0; i < n; i++) {
x[i]=0;
}
for (i = 0; i < n; i++) {
if (w[i]>c) {
break;
}else {
x[i]=1;
c-=w[i];
}
}
if (i<n) {
x[i]=c/w[i];
}
}