P3817 小A的糖果
时间:2023.10.6
题目地址:小A的糖果
题目分析
这应该是一道比较简单的贪心题了,依次索引,只需每次索引
i
n
d
e
x
index
index 让当前索引的位置和下一个位置
i
n
d
e
x
+
1
index+1
index+1 之间的糖果和小于题目给的值即可。
唯一要注意的点就是,每次先拿当前索引的下一个位置
i
n
d
e
x
+
1
index+1
index+1 的糖果,不够再拿当前的
i
n
d
e
x
index
index 就行了。
代码
n, x = map(int, input().split())
li = [int(i) for i in input().split()]
# 存放共拿了多少糖
total = 0
# 特殊情况的处理
if n == 0:
pass
elif n == 1:
if x < li[0]:
total += li[0] - x
else:
for i in range(n-1):
# 获取两个和与x的差值
temp = li[i] + li[i+1] - x
if temp > 0:
total += temp
# 优先拿i+1处的糖果
if li[i+1] >= temp:
li[i+1] -= temp
# 不够接着拿i处的糖果
else:
temp -= li[i+1]
li[i+1] = 0
li[i] -= temp
print(total)