Knapsack Problem (Greedy Algorithm)

  A greedy algorithm (also known as a greedy algorithm) means that when solving a problem, it always makes the best choice at the moment. That is to say, instead of considering the overall optimality, what he has made is a local optimal solution in a sense.

  The greedy algorithm is still a relatively easy-to-understand algorithm. I used to think so too. I feel that greedy is to achieve the optimal solution at every step, but later combined with the problem, I found that there are some problems in my understanding. One of the more classic problems of greedy algorithm is the single-source shortest path problem. I have thought about this problem for a long time on some steps, and some details cannot be figured out. I will have the opportunity to discuss this issue later. Let's talk about the backpack problem.

  The knapsack problem is that there are several items, each with its own value and weight. The backpack has an overall weight. The question is how to pack the most value from the back. There are also many kinds of knapsack problems. The greedy algorithm solves the knapsack problem where items can be split (that is, items can be divided into several parts). This problem is better solved with greed. Greedy selection means that the overall optimal solution of the problem to be sought can be achieved through a series of locally optimal selections, namely greedy selection. This is the first essential element of a greedy algorithm to be feasible, and it is also the main difference between a greedy algorithm and a dynamic programming algorithm. This problem is to regard each insertion as each step. To solve the problem, we must put each step into the optimal solution. That is to say, every time you put it in, put the best choice. Speaking of this, we need to talk about the best choice. The best choice for each insertion is that the item that is put in each time is the one with the largest value and the smallest quality among the remaining items. Here we will introduce an item. attribute, the weight value of the item. The weight value of an item is the value of the item divided by the quality of the item. Therefore, the best choice for each time of this problem is to select the item with the largest weight value each time.

  After the general idea of ​​the problem is finished, let's talk about the specific algorithm. The algorithm starts by declaring the item class first, because a lot of item attributes will be used later. If you use an array, it will be a bit troublesome. The item attributes include backpack ID, item value, item quality, and item weight value. When declaring, just enter the first three attributes of the item, and the weight value of the item can be derived from the first three. The next step of the algorithm is to sort the array of items according to the weight value of the item, and the larger weight value is placed in the front of the array, which is convenient for subsequent operations. The main body of the algorithm is to take out the item object from the array, calculate and compare the mass of the item and the remaining weight of the current backpack, and if it is greater, calculate the percentage to be put in. If it is less than, go to the next best choice. The general idea of ​​the algorithm is like this. Paste the code below:

1  package sf;
 2  
3  import java.util.Scanner;
 4  
5  public  class demo6 
 6  {
 7      // Selection sort sorts the bags in the array by weight 
8      public  static  void sort(Bag[] p)
 9      {
 10          Bag t;
 11          for ( int i=0;i<p.length;i++ )
 12          {
 13              int max= i;
 14              t= p[i];
 15              for ( int j=i;j<p.length;j++)
 16              {
 17                  if (t.wi< p[j].wi)
 18                  {
 19                      t= p[j];
 20                      max= j;
 21                  }
 22              }
 23              t= p[i];
 24              p[i]= p[max];
 25              p[max]= t;
 26              
27          }
 28      }
 29      // Knapsack problem (greedy algorithm) 
30      public  static  void bq(Bag[] p, intk, int w, double v)
 31      {
 32          if (p[k].weight< w)
 33          {
 34              v=v+ p[k].value;
 35              System.out.println(p[k].pid+"all Load, the current knapsack value is "+ v);
 36              w=w- p[k].weight;
 37              bq(p, k+1 , w, v);
 38          } else {
 39              double a=w*p[ k].wi; // Current value 
40              v=v+ a;
 41              System.out.println(p[k].pid+"Loaded"+((double )w/p[k].weight)+", the current backpack value is "+ v);
 42          }
 43          
44      }
 45      public  static  void main(String args[])
 46      {
 47          System.out.println("Please Enter the capacity w of the backpack and the number of items n" );
 48          Scanner reader = new Scanner(System.in);
 49          int w=reader.nextInt(); // The capacity of the backpack is 
50          int n=reader.nextInt() ; // Number of items 
51          Bag[] p= new Bag[n];
 52          // 10 10 a 10 10 b 10 15 c 
53         System.out.println("Please enter the weight w and value v and name s of each item in turn" );
 54          int weigth;
 55          int value;
 56          String pid;
 57          for ( int i=0;i<n;i++ )
 58          {
 59              weigth= reader.nextInt();
 60              value= reader.nextInt();
 61              pid= reader.next();
 62              p[i]= new Bag(weigth,value,pid);
 63          }
 64          // System.out.println(z[1]+""+v[1]); 
65          sort(p);
66         bq(p,0,w,0.0);
67         for(int i=0;i<n;i++)
68         {
69             System.out.println(p[i].wi+" "+p[i].pid);
70         }
71         
72     }
73 
74 }
75 
76 class Bag
77 {
78     public int weight;//重量
79     public int value;//价值
80     public double wi;//权重
81     public String pid;//背包名称
82     public  Bag(int w,int v,String pid)
83     {
84         this.weight=w;
85         this.value=v;
86         this.pid=pid;
87         this.wi=(double)value/weight;
88     }
89 }

  Most of the specific implementation problems are in the comments, although there are not many comments, let's talk about it. When typing in the console, pay attention to the fact that the item is declared first, and the object property is used. At first, I kept reporting errors. After thinking about it for a long time, I was used to using arrays, so I used array elements directly. The sorting algorithm uses selection, because selection sorting is ideal for the case of fewer elements. The main body of the greedy algorithm uses recursion. The implementation of the algorithm is relatively simple. The main purpose is to understand the idea of ​​greedy algorithm and make the choice that each step is the optimal solution.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325228556&siteId=291194637