Dynamic programming to solve the knapsack problem

X intends to travel and is told that he can carry up to 20kg of luggage. The weight of the 5 pieces of luggage that X is known to bring and its benefits during the trip are shown in the table below

Baggage number

1

2

3

4

5

Weight/kg

6

4

8

8

4

Baggage Benefit

8

4

8

10

2

In order to maximize the benefits of the luggage during the trip, which luggage should I bring?

Requirement: Please use to indicate the maximum benefit when taking out the luggage from the first i luggage and putting it into the luggage with the remaining load j .


Algorithm Design Ideas

This problem can be solved by dynamic programming algorithm. First, create the functionE function (formal parameters are the number of items n, the capacity of the backpack c, the array w that stores the weight of each item, and the array e that stores the benefits of each luggage), Through incoming data, the number of bags that will be loaded into the backpack is gradually increased in size until the maximum benefit is achieved. In the process, there are only two situations in which the current luggage is loaded or not loaded. If the weight of the luggage is less than the capacity of the current backpack, choose the operation that will produce the greatest benefit by putting the luggage in the backpack or not putting it in the backpack. If it is greater, the number of optional luggage will increase - but the benefit of the backpack will not change.

import java.util.Scanner;
 
public class dynamic programming to solve the knapsack problem {
	
	static int n;//Number of pieces of luggage
	static int c;//backpack capacity
	static int w[] ;//Luggage weight
	static int e[];//Bag benefit
	static int [][]V ;
	
	 public static void functionE(int n,int c,int w[],int e[]) {
		 for(int i=1;i<=n;i++) {//The bag number starts from 1
			 for(int j=0;j<=c;j++) {
				 if(i==0||j==0) {//When the optional luggage is 0 or the remaining capacity of the backpack is 0, the benefit is 0
					 V[i][j]=0;
				 }
				 if(j>w[i]) {//The remaining capacity of the backpack is greater than the weight of the luggage, choose the way to put it in the backpack or not put it in the backpack to produce the most benefit
					 V[i][j]=Math.max(V[i-1][j-w[i]]+e[i],V[i-1][j]);
				 }
				 else {//The remaining capacity of the backpack is less than the weight of the luggage and cannot be put into the backpack
					 V[i][j]=V[i-1][j];
				 }
			 }
		 }
	 }
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		c = in.nextInt();
		w = new int[n+1];
		e = new int[n+1];
		V = new int [n+1][c+1];
		for(int i=1;i<=n;i++) {
			w[i]=in.nextInt();
			e[i]=in.nextInt();
		}
		functionE(n,c,w,e);
		System.out.println(V[n][c]);
	}
}


Guess you like

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