日期:2025年4月16日
ZeroJudge 題目連結:j536. 不穩定的礦石 (Ore)
解題想法
分成兩次檢查吸收能量的狀況比較好寫。
Python 程式碼
使用時間約為 19 ms,記憶體約為 3.4 MB,通過測試。
import sys
for line in sys.stdin:
n, a = map(int, line.split()) # n 個礦石,吸收力 a
stone = list(map(int, input().split())) # 礦石原來的能量
p = stone.index(max(stone)) # 最多能量的礦石位置
isum = sum(stone) # 總能量
cnt, imax = 0, stone[p] # 已吸收的數量,吸收後的能量
le = p - 1 # 向左吸收的位置
# 向左吸收,最多吸收到位置 0 或是 p-a//2 為止,cnt 一定小於 a
while le >= 0 and le >= p-a//2:
cnt += 1; imax += stone[le]; le -= 1
ri = p + 1 # 向右吸收的位置
# 向右吸收,最多吸收到位置 n-1 或是 p+a//2 為止,cnt 一定小於 a
while ri < n and ri <= p+a//2:
cnt += 1; imax += stone[ri]; ri += 1
# 第二次向左吸收,最多吸收到 cnt 等於 a 或是位置 0
while cnt < a and le >= 0:
cnt += 1; imax += stone[le]; le -= 1
# 第二次向右吸收,最多吸收到 cnt 等於 a 或是位置 n-1
while cnt < a and ri < n:
cnt += 1; imax += stone[ri]; ri += 1
print(imax, isum-imax) # 印出答案