Pupils Blue Bridge Cup Python Breakthrough | Monkey Picking Fruits

Learn Python from the doll! Record the questions in the Blue Bridge Cup Python learning and test preparation process, and record every moment.

Attached is a summary post: Pupils Blue Bridge Cup Python Breakthrough | Summary_COCOgsta's Blog-CSDN Blog


【Description】

Suppose there are N (1≤N≤100) kinds of fruits in the orchard. The monkey wants to pick some fruits to take home, but the total weight of the fruits picked by the monkey cannot exceed W (1≤W≤1000).

The maximum picking quantity Ni (1≤Ni≤100) of each fruit, the weight Wi of each fruit (1≤Wi≤100) and the vitamin content Vi of each fruit (1≤Vi≤100) are known. Under the condition that the total weight of picked fruits does not exceed W, how much vitamins can monkeys obtain at most.

For example: N = 3, W = 5, which means that there are 3 kinds of fruits, and the total weight of fruits picked by monkeys cannot exceed 5.

The maximum picking amount Ni of each fruit, the weight Wi of each fruit and the vitamin content Vi of each fruit are as follows:

Take 3 of the first fruit, 1 of the second fruit, and none of the third fruit, the total volume is 5, and the maximum obtainable vitamin content is 3*2+4*1=10.

【Enter description】

Enter two positive integers in the first line to represent N, W, and the numbers are separated by spaces

In the next N lines, enter 3 positive integers in each line, representing Ni, Wi, and Vi respectively, and the numbers are separated by spaces

【Output description】

Output a number indicating how much vitamin the monkey can get at most when the total weight of the fruit picked does not exceed W

【Sample input】

3 5

4 1 2

1 2 4

2 1 1

【Sample output】

10

【Code Explanation】

N, W = [int(i) for i in input().split()]
Ni = []
Wi = []
Vi = []
for i in range(N):
    ls = [int(i) for i in input().split()]
    Ni.append(ls[0])
    Wi.append(ls[1])
    Vi.append(ls[2])

F = [0 for i in range(0, W+1)]

def CompleteBackPack(w, v):
    for i in range(w, W + 1):
        F[i] = max(F[i], F[i-w] + v)

def OneZeroBackPack(w, v):
    for i in range(W, w -1, -1):
        F[i] = max(F[i], F[i-w] + v)


def MultipleBackPack(w, v, n):
    if w * n >= W:
        CompleteBackPack(Wi[i], Vi[i])
        return
    temp_n = 1
    while temp_n < n:
        OneZeroBackPack(temp_n * w, temp_n * v)
        n -= temp_n
        temp_n *= 2
    OneZeroBackPack(n * w, n * v)

for i in range(0, N):
    MultipleBackPack(Wi[i], Vi[i], Ni[i])

print(F[W])
复制代码

【operation result】

3 5
4 1 2
1 2 4
2 1 1
10

 

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/129772846#comments_25816911