有一个代码
n, m = map(int, input('').split())
grades = list(map(int, input().split()))
def calculate(m, grades):
result = 0
for i in range(m):
if grades[i] != 0:
result += grades[i]**2
counter = 0
for j in range(i + 1, m):
if counter == grades[i]:
break
if grades[j] != 0:
result += grades[j]
counter += 1
return result
print(calculate(m, grades))


创建一个附加列表,您可以在其中收集累积(累计)数量的非零评级。例如,对于
gr = [1,0,2,0,0,3,0,4]这将是cs = [1,3,6,10].а要找到从到的单元格的部分和b,您需要减去cs[b]-cs[a-1]。列表从末尾开始遍历,
cs当 in 的值非零时,in 的索引会减少gr。原则上,可以通过删除零来压缩原始列表,但这不会从根本上改善任何事情,因为 解将是线性的