Code:
- package algorithm;
-
-
-
-
- public class Knapsack {
-
- private float m ;
- private float[] v ;
- private float[] w ;
- private float[] x ;
- private int n ;
- double[] p_w_v ;
-
- public Knapsack(){
-
- this.m = 50.0f ;
- this.v = new float[]{60.0f,120.0f,100.0f} ;
- this.w = new float[]{10.0f,30.0f,20.0f} ;
- this.x = new float[3] ;
- this.n = 3 ;
- this.p_w_v = new double[n] ;
- }
-
-
- public void sort(int n , float[] v ,float[] w)throws Exception{
-
- for (int i = 0 ; i < n ; i++){
- p_w_v[i] = v[i] / w[i] ;
- }
- print (p_w_v);
- System.out.println ("");
- insertSort(p_w_v,w,v) ;
- print (p_w_v);
- }
-
- public void print (double a[]){
- int len = a.length;
- for (int i = 0; i < len; i++){
- System.out.print(a[i] + " ");
- }
- }
-
- public void print (String str){
- System.out.print(str + "/n");
- }
-
- public void insertSort(double[] a , float[] b , float[] c){
- int len = a.length;
- double temp;
- float w_temp ;
- float v_temp ;
- for (int i = 0; i < len-1; i++){
- for (int j = 0; j < len-1-i; j++){
- if (a[j+1] > a[j]){
-
- temp = a[j+1];
- w_temp = w[j+1];
- v_temp = v[j+1];
-
- a[j+1] = a[j];
- w[j+1] = w[j];
- v[j+1] = v[j];
-
- w[j] = w_temp;
- v[j] = v_temp;
- }
- }
- }
- }
-
-
- public void knapsack()throws Exception{
- sort (n , v , w) ;
- int i ;
- for (i = 0 ; i < n ; i++){
- x[i] = 0 ;
- }
- float c = m ;
- for (i = 0 ; i < n ; i++){
- if (w[i] > c){
- break ;
- }
- x[i] = 1 ;
- c -= w[i] ;
- }
- if (i < n){
- x[i] = c / w[i] ;
- }
- print ("/n物品一可以装入的比例: " + x[0]);
- print ("物品二可以装入的比例: " + x[1]);
- print ("物品三可以装入的比例: " + x[2]);
- print ("可以装入的最大价值为: " + (x[0]*v[0] + x[1]*v[1] + x[2]*v[2]));
- print ("可以装入的最大重量为" + (x[0]*w[0] + x[1]*w[1] + x[2]*w[2]));
- }
-
- public static void main (String[] args)throws Exception{
- Knapsack ksp = new Knapsack();
- ksp.knapsack();
- }
- }