# import sys
# sys.stdin = open("tra.txt", "r")
import heapq
n, k = map(int, input().split())
sciez = list(map(int, input().split()))
heap = [(-wys, index) for index, wys in enumerate(sciez)]
obsluzone = set()
heapq.heapify(heap)
ciezarowek = 0
while (len(obsluzone) < n):
wys, index = heapq.heappop(heap)
wys = -wys
if not index in obsluzone:
obsluzone.add(index)
if (index > 0) and (not (index-1) in obsluzone):
roz = sciez[index] - sciez[index-1]
if roz > k:
ciezarowek+= roz-k
sciez[index-1]+= roz-k
heapq.heappush(heap, (-sciez[index-1], index-1))
if (index < n-1) and (not (index+1) in obsluzone) :
roz = sciez[index] - sciez[index+1]
if roz > k:
ciezarowek+= roz-k
sciez[index+1]+= roz-k
heapq.heappush(heap, (-sciez[index+1], index+1))
print(ciezarowek)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | # import sys # sys.stdin = open("tra.txt", "r") import heapq n, k = map(int, input().split()) sciez = list(map(int, input().split())) heap = [(-wys, index) for index, wys in enumerate(sciez)] obsluzone = set() heapq.heapify(heap) ciezarowek = 0 while (len(obsluzone) < n): wys, index = heapq.heappop(heap) wys = -wys if not index in obsluzone: obsluzone.add(index) if (index > 0) and (not (index-1) in obsluzone): roz = sciez[index] - sciez[index-1] if roz > k: ciezarowek+= roz-k sciez[index-1]+= roz-k heapq.heappush(heap, (-sciez[index-1], index-1)) if (index < n-1) and (not (index+1) in obsluzone) : roz = sciez[index] - sciez[index+1] if roz > k: ciezarowek+= roz-k sciez[index+1]+= roz-k heapq.heappush(heap, (-sciez[index+1], index+1)) print(ciezarowek) |
English