程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Blue Bridge Cup algorithm training boring funny Python 100 points

編輯:Python

Typical knapsack problem , Use a two-dimensional matrix to record the state

n = int(input())
sticks = list(map(int, input().split()))
volumn = sum(sticks) // 2 + 1
# The volume of the backpack
res_map = [[-1 for _ in range(n + 1)] for _ in range(volumn)]
res_map[0][0] = 0

Index records with the first dimension “ The longest stick ” - “ Secondary bar ”, The second dimension index record “ Have considered before n A stick ”, Corresponding cell record “ The longest stick ” And “ Secondary bar ” Length of equal length part

The reason why the backpack volume is so set is : To combine equal length rods , therefore “ The longest stick ” - “ Secondary bar ” <= sum(sticks) // 2

Every time the stick is taken into account , Can choose :

  1. Not with “ The longest stick ”、“ Secondary bar ” superposition
  2. And “ The longest stick ” superposition
  3. And “ Secondary bar ” superposition
  4. And “ Secondary bar ” superposition ,“ Secondary bar ” Turn into “ The longest stick ”,“ The longest stick ” Turn into “ Secondary bar ”
for idx in range(1, n + 1):
# The first idx Add a stick to the consideration
for res in range(volumn):
stick = sticks[idx - 1]
res_map[res][idx] = res_map[res][idx - 1]
# Not with ” The longest stick ”、“ Secondary bar ” superposition , Direct transfer status
last_state = res - stick
# Find a state to pass
if last_state >= 0:
# Judge whether the status is legal
last_value = res_map[last_state][idx - 1]
if last_value >= 0:
res_map[res][idx] = last_value
# And “ The longest stick ” superposition , The equal length part does not change
last_state = res + stick
if last_state < volumn:
last_value = res_map[last_state][idx - 1]
if last_value >= 0:
res_map[res][idx] = max([res_map[res][idx], last_value + stick])
# And “ Secondary bar ” superposition , The isometric part changes ———— Compare and take the best
last_state = stick - res
if last_state >= 0:
last_value = res_map[last_state][idx - 1]
if last_value >= 0:
res_map[res][idx] = max([res_map[res][idx], last_value + stick - res])
# And “ Secondary bar ” superposition ,“ Secondary bar ” Turn into “ The longest stick ”,“ The longest stick ” Turn into “ Secondary bar ”, The isometric part changes ———— Compare and take the best 

The end result is “ The longest stick ” - “ Secondary bar ” = 0, And consider all the sticks , Corresponding res_map[0][-1],print come out

Full marks end


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved