1. 程式人生 > >背包問題(貪心策略)

背包問題(貪心策略)

print strong 最大 code sta ring 優先 ati n+1

原創


給定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

背包問題(貪心策略)