背包问题(贪心策略)

原创


给定n种物品和一个背包。物品i的重量是Wi,其价值为Vi,背包的容量为C。应如何选择装入背包的物品,

使得装入背包中物品的总价值最大?物品时可以拆分的,比如可以将物品的三分之一放入背包。

使用优先放入【价值/重量】最大的物品的贪心策略解题。

 1 import java.util.Scanner;
 2 class sack{    //背包类
 3     private double c;    //背包容量
 4     private double n;    //物品个数
 5     private double w[];    //重量
 6     private double v[];    //价值
 7     private double x[];    //结果向量
 8     public void sort(){
 9         for(int i=1;i<n;i++){
10             for(int j=1;j<n;j++){
11                 if(v[j]/w[j]<v[j+1]/w[j+1]){
12                     double temp;
13                     temp=v[j];
14                     v[j]=v[j+1];
15                     v[j+1]=temp;
16                     temp=w[j];
17                     w[j]=w[j+1];
18                     w[j+1]=temp;
19                 }
20             }
21         }
22     }
23     public sack(double c,double n,double w[],double v[],double x[]){
24         this.c=c;
25         this.n=n;
26         this.w=w;
27         this.v=v;
28         this.x=x;
29     }
30     public double knapsack(){
31         sort();
32         double total=0;
33         for(int i=1;i<=n;i++){
34             x[i]=0;
35         }
36         int i=1;
37         while(w[i]<c){
38             x[i]=1;
39             total+=v[i];
40             c-=w[i];
41             i++;
42         }
43         x[i]=c/w[i];
44         total+=x[i]*v[i];
45         return total;
46     }
47 }
48 public class knapSack {
49 
50     public static void main(String[] args) {
51         System.out.print("input n:");
52         Scanner reader=new Scanner(System.in);
53         int n=reader.nextInt();
54         System.out.print("input c:");
55         double c=reader.nextDouble();
56         System.out.print("input weight:");
57         double w[]=new double[n+1];
58         for(int i=1;i<=n;i++){
59             w[i]=reader.nextDouble();
60         }
61         System.out.print("input value:");
62         double v[]=new double[n+1];
63         for(int i=1;i<=n;i++){
64             v[i]=reader.nextDouble();
65         }
66         double x[]=new double[n+1];
67         sack sa=new sack(c,n,w,v,x);
68         System.out.println("bestvalue: "+sa.knapsack());
69     }
70 
71 }

23:21:16

2018-11-02

猜你喜欢

转载自www.cnblogs.com/chiweiming/p/9899065.html