Backpack Issue - 04 Hybrid Backpack

After the introduction of the previous three kinds of knapsack problems, based on these three kinds of knapsack problems, the mixed form of these three types can be derived - the mixed knapsack problem. It can be mixed in two or three. It is nothing more than classifying and combining each item according to the number of occurrences during the analysis.

Assumptions: Define the total accommodated weight W = 10 Kg, the item type N = 3, the weight of each item w[i], and the corresponding value v[i], and find out how to select the maximum value within the accommodated weight range.

Specific topics:


Possible situations:


Since the use of two-dimensional arrays is cumbersome, only one-dimensional array solutions are given using the following:

//One-dimensional array solution - mixed knapsack
	private static int[] BP_method04_1D(int m,int n,int[] w,int[] v,int[] counts){
		int c[] = new int[m+1];
		for (int i = 0; i < m+1; i++) {
			c[i] = 0;//It does not have to be completely filled, then all are initialized to 0
		}
		for (int i = 0; i < n; i++) {
			//Multiple backpacks
			for(int k = 1; k < counts[i]; k <<= 1){
					for (int j = m; j >= k * w[i]; j--) {//limit the total weight
						c[j] = Math.max(c[j-k*w[i]] + k*v[i], c[j]);
					}
				counts[i] -= k;
			}
			if (counts[i] == 1) {//01 backpack
				for (int j = m; j >= w[i]; j--) {//limit the total weight
					c[j] = Math.max(c[j-w[i]] + v[i], c[j]);
				}
			}else{//complete backpack
				for (int j = w[i]; j < m+1; j++) {//limit the total weight
					c[j] = Math.max(c[j-w[i]] + v[i], c[j]);
				}
			}
		}
		return c;
	}

Its output is as follows:

One-dimensional array solution:
0 0 0 4 5 6 6 9 10 11 12


Guess you like

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