# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
633078 | karolb2011 | Potatoes and fertilizers (LMIO19_bulves) | Cpython 3 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
import sys
import heapq as hq
input = sys.stdin.readline
n=int(input())
t=0
p=0
s=[]
ww=0
z=[]
for i in range(n):
pi,bi=list(map(int,input().split()))
p+=bi-pi
s.append(p)
if p==0:
for c in s:
ww+=abs(c)
elif p==-1:
for c in s:
if c<=-1:
ww-=c
t-=c+1
else:
ww+=c
t+=c+1
z.append(ww-t)
ww=min(t,min(z)+t)
else:
w=[]
for c in s:
if c>0:
ww+=c
c=0
elif c<p:
ww-=c-p
c=p
hq.heappush(w,c)
if w[0]<c:
hq.heappush(w,c)
ww+=abs(hq.heappop(w)-c)
print(ww