According to the order of "Nine Lectures on Backpacks", this article mainly focuses on the seventh lecture - Dependent Backpacks. The so-called "reliance on backpacks" means that the backpack objects have main accessories. Similar explanations have been mentioned in "Two-dimensional Cost Backpacks" before, but The main attachment here is a subordinate relationship, that is, to select the main component, you must select the attachment, and there can be many types of attachments, and the same attachment can also have attachments. The result and the situation considered will grow exponentially, so it cannot be written as an equation like "01 knapsack", but if given constraints, we can also convert it into something like "01 knapsack" or "complete knapsack", etc. form to solve.
The title designed in this article is the Huawei OJ question of Niuke.com - shopping list.
Problem Description:
Main items | Appendix |
computer | printer, scanner |
bookcase | books |
desk | desk lamp, stationery |
work chair | without |
Enter description:
The first line of input, two positive integers, separated by a space: N m
Output description:
The output file has only one positive integer, which is the maximum value (<200000) of the sum of the product of the price and the importance of the item that does not exceed the total amount of money.
The specific topics are as follows:
The specific Java implementation code is as follows:
//Here is explained with a one-dimensional array private static int bp_rely(int m,int n,int[] w,int[] v,int[] q){ int[] c = new int[m+1]; for (int i = 0; i < m+1; i++) { c[i] = 0; } List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.clear(); if (q[i] == 0) { for (int j = m; j >= w[i]; j--) { list.add( Math.max(c[j-w[i]] + v[i], c[j])); c[j] = Math.max(c[j-w[i]] + v[i], c[j]); } }else { for (int j = m; j >= (w[i]+w[q[i]]); j--) { list.add(Math.max(c[j-w[i]-w[q[i]]] + v[q[i]], c[j])); c[j] = Math.max(c[j-w[i]-w[q[i]]] + v[q[i]], c[j]); } } } int max = Collections.max(list); return max; }
In the above code, it should be noted that whether the object is a "main part" or an "accessory" is determined by judging whether q is "0", and if it is an accessory, the main part must be purchased before the accessory can be purchased, that is, the following code :
Math.max(c[jw[i]-w[q[i]]] + v[q[i]], c[j]) //w[i] and w[q[i]] are the main ones prices of parts and accessories
If there are any flaws or mistakes in the above, please criticize and correct.