Hihocode----knapsack problem

Source: Internet
Author: User
Tags ticket
0-1 knapsack problem

In the story of the last week, Little Hi and Little Ho struggled to get a lot of lottery tickets. And now it's time for Little Ho to pick up the reward.

Little Ho now has an M-ticket on his hand, and the prize area has n the prize, respectively the marking is 1 to n, in which I the prize needs to need (i) the ticket to exchange, simultaneously also can only exchange once, in order to make the lottery not to be wasted, small Ho gives each prize to evaluate the cent, The value (i) of the prize in Part I represents his preference for the prize. Now he wondered what prizes could be exchanged for the prizes in his hands, so that the sum of their preferences could be maximized.
The idea of solving problems: enumerating the possible options of 2^n, first calculating the sum of the lottery tickets they need, and calculating the sum of their preferences and value in the case of sums not exceeding m, and counting an optimal scheme, that is, the maximum value of value. Time complexity O (2^n), violent method is not advisable. Consider dynamic planning.
First, we have to think of ways to abstract the problems we now encounter. With Best (i, J) It has been decided whether the first I item is selected, the sum of the highest preference values that can be obtained when the total number of lottery tickets for the currently selected item does not exceed J. For any i>1, J, we can all know best (i, J) =max{best (I-1, J-need (i)) + value (i), Best (I-1, J)}.
Check to see if the definition of the problem has two properties that are required for dynamic programming: Repeat child problems and no no validity.
First look at the repeat child problem-this is why dynamic planning is more efficient than search, if the last four prizes are 1 for the lottery, preference value is 1, the required lottery is 2, the preference is 2, the lottery is 3, the preference value is 3, the lottery is 4, the preference value is 4 of four prizes, then whether it is to choose 1, 4 or 2, 3, will require the solution best (N-4, M-5) Such a child problem, and this child problem only need to solve one time to be able to calculate, so the duplicate child problem this property is satisfied.
Second, see no effect ... Similarly, if a lottery ticket is required to be 1, the preference is 1, the lottery is 2, the preference value is 2, for a lottery of 3, a preference of 3, a lottery for 4 and four prizes of 4 preference, either the 1th and 4th, or the 2nd and 3rd, are required to have a lottery number of 5, The sum of preference value is 5. So I just need to know that best (4, 5) =5 is enough, and why it equals 5 is no different to me, and will not affect subsequent decisions. This is no effect, so it is satisfying to want to come.
Then the next thing to consider is how to use Best (i, J) =max{best (I-1, J-need (i)) + value (i), Good (I-1, J)} to solve each of the good (I, j). We define a problem a depends on another problem B when and only if you need to know the value of B beforehand in the process of solving a It is easy to see that best (I, j) is dependent on best (i-1, J-need (i)) and Best (I-1, J) Two questions, That is to say, the two problems need to be solved before best (i, J). So we just follow the I small to large order, in this way to calculate, it can be.
Time complexity has been optimized to O (NM). The next step is to optimize the complexity of space.
According to the above idea, you need to open a n * M size of two-dimensional array best, to record the best value of the solution. But we only need to i-1 the data when calculating I, so the space can be optimized to 2*m. Further, it is only necessary to open a one-dimensional array of M size. If I were to compute the order of J from M to 1, which is the reverse order. In addition, according to our state transition equation, it is obvious that if the state (IA, JA) depends on the state (IB, JB), then there must be IA = ib+1, ja>=jb. So it is not difficult to draw a conclusion: I am in the calculation of best (I, j), because the good (I, J+1..M) these states have been computed, so it means the good (i-1, K), K=j. M these values are useless-all the values that depend on them have been computed. So that their original storage space can be used to store other things, so I do not imitate the best (i, j) values exist in the original position of best (I-1, J).

Import java.util.*;

public class Main {public
    static void Main (string[] args) {
        Scanner cin = new Scanner (system.in);
        while (Cin.hasnext ()) {
            int N = Cin.nextint ();//n Prizes
            int M = Cin.nextint ();/M Zhang Yi
            int[] need = new int[n+1];
            int[] value = new int[n+1];
            for (int i=1; i<=n; i++) {
                Need[i] = Cin.nextint ();
                Value[i] = Cin.nextint ();
            }

            Int[] f = new int[m+1];
            for (int i=1; i<=n; i++) {
                for (int j=m; j>=0; j--) {
                    if (J >= Need[i]) {
                        F[j] = Math.max (f[j), f[j-n Eed[i]] + value[i]);
                    }
                }
            System.out.println (F[m]);}}
Full knapsack problem

In the story before, Little Hi and Little Ho struggled to finally get the vast number of lottery tickets. And now it's time for Little Ho to pick up the reward.

Wait, why is this story familiar? This is going to start with the theory of the parallel universe ... All in all, in another universe, small ho faces a slight change in the problem.

Little Ho now has an M-ticket on his hand, and the prize area has n kinds of prizes, respectively labeled 1 to N, of which the first prize needs to need (i) tickets for the exchange, and can be exchanged countless times, in order to make hard-earned lottery not wasted, small ho to each of the prizes are graded, The value (i) of the prize in Part I represents his preference for the prize. Now he wondered what prizes could be exchanged for the prizes in his hands, so that the sum of their preferences could be maximized.
Idea: According to the idea of 01 backpacks, I can use Best (i, J) said that it had been decided how many items to choose for each item of the first I item, the sum of the highest preferences that the currently selected item had not been able to obtain when the total number of lottery tickets were not more than J, the final answer would be best (N, M). For a problem best (I, J), consider the last step-that is, the choice of how many pieces of items, it may be assumed to choose the K-piece, then K's range of values must be in the range of 0~ (J/need (i)). At this time we can know Best (i-1, J-need (i) * k) + value (i) * k will be a possible solution. Best (i, j) = Max (Best (I-1, J-need (i) * k) + value (i) * k), 0 <= k <= j/need (i). We can further optimize the substructure. The sub-problem is refined to the selection of each item, for example, when we select the piece of the item k, it is possible to take advantage of the k-1 pieces of the article I information. So, best (i, j) = Max (Best (I-1, J), Best (I, j-need (i)) + value (i)). The first case is a piece I do not choose, the second case is that I have selected the k-1 on the basis of the selection of a I.
Similar to the 0-1 knapsack problem, in order to optimize the space complexity, we will iterate the J according to the order from 0 to M. As you can see, the only difference between the code and the 0-1 knapsack problem is one line.

import java.util.*;
        public class Main {public static void main (string[] args) {Scanner cin = new Scanner (system.in);
            while (Cin.hasnext ()) {int N = Cin.nextint ();
            int M = Cin.nextint ();
            int[] Need = new int[n+1];
            int[] value = new int[n+1];
                for (int i=1; i<=n; i++) {Need[i] = Cin.nextint ();
            Value[i] = Cin.nextint ();
            } int[] f = new int[m+1];
                        for (int i=1; i<=n; i++) {for (int j=0; j<=m; J + +) {if (need[i) <= j) {
                    F[J] = Math.max (F[j], f[j-need[i]]+value[i]);
        }} System.out.println (F[m]); }
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.