Data Structures and Algorithms: Dynamic Programming

The classic 01 knapsack problem: given a few items, each item has a different kind of value, but not the same weight, in seeking a maximum value can withstand the weight of the backpack W's can hold items (probably so description)

Similar topics:  https://www.luogu.org/problem/P1048  probably means: the valley, there are a few herbs, herbal value of each one is different, not the same acquisition takes time, seeking to be able to collect a given time the maximum value of herbs

Java Solution:

    public  static  void main (String [] args) { 
        Integer M = . 3 ;   // herbal total number 
        Integer T = 70 ; // total usable time 

        Integer Result = 0 ; // total final value 

        // following two arrays this line must be 0, because initialization 
        int [] = V new new  int [] { 0 , 100 , . 1 , 2 }; // herbal value 
        int [] = W new new  int [] { 0 , 71 is ,69 , 1 }; // time required 

        // I of this herb, j is the current time remaining
         // if not taken: State [I] [J] = State [J-1] [J]
         @ If taken: State [I] [J] = State [I-. 1] [JW [I]] + V [I] 

        int [] [] State = new new  int [M + . 1 ] [T + . 1 ]; 

        for ( int I = . 1 ; I <= M; I ++ ) {
             for ( int J = 0 ; J <= T; J ++ ) {
                 IF (J> = W [I]) { // if the current time sufficient acquisition Zheke herbs taken collected or not collected among that a large value
                    state[i][j] = state[i-1][j] > state[i-1][j-w[i]] + v[i] ? state[i-1][j] : state[i-1][j-w[i]] + v[i];
                } else { // 否则不采
                    state[i][j] = state[i-1][j];
                }
                if (state[i][j] > result) {
                    result = state[i][j];
                }
            }
        }
        System.out.println("最大价值: " + result);
    }

Performance and weight of the backpack dynamic programming or is this subject among the total time T can have a relationship, if this number is too large, the performance of dynamic programming but will greatly decrease

Guess you like

Origin www.cnblogs.com/cccy0/p/11586283.html