Dynamic Programming - miner mining

Dynamic programming three elements: border, sub-optimal problem, the state transition equation;

Problem Description: The existing 10 miners, five gold, each corresponding to the number of gold and gold has to be mined, and asked how much gold can get you up to?

This is a typical problem of dynamic programming, dynamic programming core of the problem is how to convert into overlapping sub-problems, and write the state transition equation.

First, we define the corresponding parameters:

The number of miners: n = 10

The number of gold: w = 5

Number of gold: g = [400,500,200,300,350]

The number of needs: p = [5,5,3,4,4]

p [i] represents the i-th gold digging required number, g [i] represents the number of i-dug gold mine gold obtained. So that F (n, w) represents the maximum number of gold n w a personal dig gold can get.

When the number n <p [i], that is the i-th gold digging is not enough, you can now get the maximum number of gold digging for gold is the first time i-1 gold mines:

F(n,w)=F(n,w-1)

When we n> p [i], the following equation:

F(n,w)=max(F(n,w-1),F(n-p[i],w-1)+g[i])

 

N represents the maximum number of individual gold digging gold can be obtained in the w = max (w-1 n individual dig gold mines, ((np [i]) w-1 personal dug gold mine) + g [i]) )

The final code:

10 = n- 
W =. 5 
G = [400,500,200,300,350 ] 
P = [5,5,3,4,3 ]
 DEF goldMining (n-, W, G, P):
     # initialize an array, for storing information, note that in order to better calculate a total of 11 columns, the first auxiliary bit as 
    DP = [[0 for _ in Range (n-+. 1)] for _ in Range (W)]
     # boundary 10 is first dug only one individual gold 
    # [0, 0, 0, 0, 0, 400, 400, 400, 400, 400, 400] 
    for I in Range (. 1, n-+. 1 ):
         IF I < P [0]: 
            DP [0] [I] = 0
         the else : 
            DP [0] [I]= G [0]
     # , traversing gold number 
    for I in Range (. 1 , W):
         for J in Range (. 1,. 1 n-+ ):
             # If the number is less than the current number of this gold digging 
            IF J < P [I]:
                 # the current value corresponding to the maximum number of gold is a gold front digging 
                dp [i] [J] = dp [i-. 1 ] [J]
             the else :
                 # otherwise is calculated by the following equation 
                dp [i ] [J] = max (DP [I-. 1] [J], DP [I-. 1] [JP [I]] + G [I])
     return DP 

DP = goldMining (n-, W, G, P)
 for i in the Range (len (dp)):
    print(dp[i])

Final result:

 

We can see, the maximum number of gold we can finally get is 900, which is to dig first and second gold. 

Guess you like

Origin www.cnblogs.com/xiximayou/p/11964509.html