动规背包问题实现:
import java.util.Scanner;
public class PackDynamic {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] v = new int[100];
int[] w = new int[100];
int[] x = new int[100];
float[][] m = new float[100][100];
v[0] = 0;
w[0] = 0;
int n = sc.nextInt();
for (int i = 1; i <= n; i++) {
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
int c = sc.nextInt();
for (int i = 1; i <= n; i++) {
int count=w[i];
for (int j = 1; j <= c; j++) {
if(m[i - 1][j]<m[i][j-1]+(float)v[i]/w[i])
if(count>0)
{
m[i][j] = m[i][j-1]+(float)v[i]/w[i];
x[i]++;
count--;
} else {
m[i][j] = v[i]+m[i - 1][j-w[i]];
}
else
{
m[i][j]=m[i-1][j];
}
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= c; j++) {
System.out.print(m[i][j]+" ");
}
System.out.println();
}
System.out.println(m[n][c]);
for (int i = 1; i <= n; i++) {
System.out.println(x[i]);
}
sc.close();
}
}
贪心背包实现:
package compu_Second;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class PackGreekdy {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
ArrayList<Goods> al=new ArrayList<Goods>();
int packCapa=sc.nextInt();
int goodsNum=sc.nextInt();
int num=1;
for(int i=1;i<=goodsNum;i++) {
int weight=sc.nextInt();
int value=sc.nextInt();
float unit_value=(float)value/(float)weight;
al.add(new Goods(weight,value,unit_value,0,num));
num++;
}
al.sort(new Comparator<Goods>() {
public int compare(Goods o1, Goods o2) {
// TODO Auto-generated method stub
if(o2.unit_value-o1.unit_value>0) {
return 1;
}else {
return -1;
}
}
});
int countNum=0;
for(Goods g:al) {
if((countNum+g.weight)<=packCapa) {
countNum+=g.weight;
g.x=g.weight;
}else {
g.x=packCapa-countNum;
break;
}
}
ArrayList<Goods> alpack=new ArrayList<Goods>();
for(Goods g:al) {
if(g.x>0) {
alpack.add(g);
}
}
alpack.sort(new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
return o1.num-o2.num;
}
});
float totalValue=0;
for(Goods g:alpack) {
System.out.println(" "+g.num+" "+g.x);
totalValue+=g.x*g.unit_value;
}
System.out.println(totalValue);
sc.close();
}
}
class Goods{
int weight;
int value;
float unit_value;
float x;
int num;
public Goods() {
super();
// TODO Auto-generated constructor stub
}
public Goods(int weight, int value, float unit_value, float x,int num) {
this.weight = weight;
this.value = value;
this.unit_value = unit_value;
this.x = x;
this.num=num;
}
}