Problem:
 Score: 500 points    Problem Statement  In the Kingdom of AtCoder, only banknotes are used as currency. There are 10^{100}+1 kinds of banknotes, with the values of 1, 10, 10^2, 10^3, \dots, 10^{(10^{100})} . You have come shopping at a mall and are now buying a takoyaki machine with a value of N . (Takoyaki is the name of a Japanese snack.)  To make the payment, you will choose some amount of money which is at least N and give it to the clerk. Then, the clerk gives you back the change, which is the amount of money you give minus N .  What will be the minimum possible number of total banknotes used by you and the clerk, when both choose the combination of banknotes to minimize this count?  Assume that you have sufficient numbers of banknotes, and so does the clerk.      Constraints   N is an integer between 1 and 10^{1,000,000} (inclusive).         Input  Input is given from Standard Input in the following format:  N       Output  Print the minimum possible number of total banknotes used by you and the clerk.        Sample Input 1 36      Sample Output 1 8  If you give four banknotes of value 10 each, and the clerk gives you back four banknotes of value 1 each, a total of eight banknotes are used.  The payment cannot be made with less than eight banknotes in total, so the answer is 8 .       Sample Input 2 91      Sample Output 2 3  If you give two banknotes of value 100, 1 , and the clerk gives you back one banknote of value 10 , a total of three banknotes are used.       Sample Input 3 314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170      Sample Output 3 243

Solution (Python):

N = list(input())

N.reverse()

ans = 0
flag = False
L = len(N)
for i,s in enumerate(N):
    n = int(s)
    
    if flag:
        n += 1
    
    if n<5:
        ans += n
        flag = False
    elif n>5:
        ans += 10-n
        flag = True
    else:
        if i==L-1:
            ans += n
            flag = False
            break
            
        if int(N[i+1])<5:
            ans += n
            flag = False
        else:
            ans += 10-n
            flag = True

if flag:
    ans += 1
    
print(ans)

Solution (Python):
l=[0]+[int(i) for i in input()]
l.reverse()
su=0
for i in range(len(l)):
    if l[i]>5:
        l[i]=10-l[i]
        l[i+1]+=1
    elif l[i]==5 and l[i+1]>4:
        l[i+1]+=1
    su+=l[i]
print(su)

Solution (Python):
n=input()
ans=0
x=-1
n=n+str(0)
for i in range(len(n)-1):
    v=int(n[i])
    w=int(n[i+1])
    if x<0:
        if v<5:
            ans+=v
        elif v==5:
            if w>=5:
                ans+=9-v+2
                x+=1
            else:
                ans+=v
        else:
            ans+=9-v+2
            x+=1
    else:
        if v<4:
            ans+=v
            x-=1
        elif v==4:
            if w>=5:
                ans+=9-v
            else:
                ans+=v
                x-=1
        else:
            ans+=9-v

print(ans)

Solution (Python):



n = str(input())


'''
a = []
for i in range(l):
    if m[i] <= 5:
        a.append(0)
    elif m[i] > 5:
        a.append(1)

for i in range(l):
    if i < l-1 and a[i+1] == 1 and m[i] == 5:
        a[i] = 1

p = []
for i in range(l):
    if a[i] == 0:
        if i < l-1 and a[i+1] == 1:
            p.append(m[i]+1)
        else:
            p.append(m[i])
    elif a[i] == 1:
        p.append(0)

pp = ''
for i in range(l):
    pp += str(p[i])
if pp[0] == '0':
    pp = '1' + pp
pp = int(pp)
oo = pp - n
print(pp)
print(oo)
ppp = [int(str(pp)[i]) for i in range(len(str(pp)))]
ooo = [int(str(oo)[i]) for i in range(len(str(oo)))]

print(sum(ppp) + sum(ooo))
'''
dp = [0, 1] 

for i in n:
    i = int(i)
    dp0 = dp[0]
    dp1 = dp[1]
    dp[0] = min(dp0 + i, dp1 + (10 - i))
    dp[1] = min(dp0 + i + 1, dp1 + (10 - i) - 1)
print(dp[0])

Solution (Python):
S = input()
l = len(S)
dp = [[0]*2 for _ in range(l+1)]
dp[1][0]=min(dp[0][1]+10-int(S[0])+1,dp[0][0]+int(S[0]))
dp[1][1]=min(dp[0][1]+10-int(S[0])-1+1,dp[0][0]+int(S[0])+1)
for i in range(1,l):
  dp[i+1][0]=min(dp[i][1]+10-int(S[i]),dp[i][0]+int(S[i]))
  dp[i+1][1]=min(dp[i][1]+10-int(S[i])-1,dp[i][0]+int(S[i])+1)
print(dp[-1][0])

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import log10, ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
import numpy as np

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = input()

dp = (0, 1)  
for i in N:
	i = int(i)
	dp = (min(dp[0] + i, dp[1] + 10 - i), min(dp[0] + i + 1, dp[1] + 9 - i))
print(dp[0])

Solution (Python):
a=b=0
for n in map(int,'0'+input()):a,b=n+min(a,b),9-n+min(b,a+2)
print(min(a,b))

Solution (Python):
a=b=0
for n in map(int,'0'+input()):a,b=n+min(a,b),9-n+min(b,a+2)
print(min(a,b))

Solution (Python):
digits = [0] + [int(c) for c in input()]

dp = [0, 1]
for digit in reversed(digits):
    dp0, dp1 = dp
    dp[0] = min(dp0, dp1 + 1) + digit
    dp[1] = min(dp0, dp1 - 1) + 10 - digit

print(min(dp))

Solution (Python):


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))


n = input()
m = len(n)
n = n[::-1] + '0'

dp = [[inf]*2 for _ in range(m+1)]
dp[0][0] = 0
for i in range(m):
    x = int(n[i])
    for j in range(2):
        x += j
        for a in range(10):
            b = a-x
            if a >= x:
                dp[i+1][0] = min(dp[i+1][0],dp[i][j]+a+b)
            else:
                dp[i+1][1] = min(dp[i+1][1],dp[i][j]+a+10+b)
ans = min(dp[-1][0],dp[-1][1]+1)
print(ans)

Solution (Python):
N = [int(i) for i in input()]

dp = [0, float('inf')]

for n in N :
  ndp = [0] * 2
  ndp[0] = min(dp[0] + n, dp[1] + n)
  ndp[1] = min(dp[0] + 11 - n, dp[1] + 9 - n)
  dp = ndp

print(min(dp[0], dp[1]))

Solution (Python):
s = input()
nums = list(reversed([int(c) for c in s])) + [0]
r = (0, 1) 
for i in range(len(nums)):
    
    next_no_borrow = min(r[0] + nums[i], r[1] + nums[i] + 1)
    next_borrow = min(10 - nums[i] + r[0], 9 - nums[i] + r[1])
    r = (next_no_borrow, next_borrow)
print(min(r))

Solution (Python):


import sys
import math
import itertools

def main():
    ns = list(map(int, sys.stdin.readline().strip()))
    ns.reverse()
    ns.append(0)

    ans = 0
    lastpay = 0

    for i in range(len(ns)):
        if lastpay == 0:
            if ns[i] <= 4 or (ns[i] == 5 and ns[i + 1] <= 4):
                ans += ns[i]
                lastpay = 0
            else:
                ans += 1 + (10 - ns[i])
                lastpay = 1
        else:
            if lastpay + ns[i] <= 4 or (lastpay + ns[i] == 5 and ns[i + 1] <= 4):
                ans += ns[i]
                lastpay = 0
            else:
                ans += 1 - 1 + (9 - ns[i])
                lastpay = 1
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
n = list(map(int, input()))
dp = (0, 1)
for i in n:
  dp = (min(dp[0] + i, dp[1] + 10 - i), min(dp[0] + i + 1, dp[1] + 9 - i))
print(dp[0])

Solution (Python):
S = input()[::-1]
l = len(S)
dp = [[0]*2 for _ in range(l+1)]
for i in range(l):
  dp[i+1][0]=min(dp[i][0]+int(S[i]),dp[i][1]+int(S[i])+1)
  if i!=0:
    dp[i+1][1]=min(dp[i][0]+10-int(S[i]),dp[i][1]+10-(int(S[i])+1))
  else:
    dp[i+1][1]=dp[i][0]+10-int(S[i])
print(min(dp[-1][0],dp[-1][1]+1))

Solution (Python):
n = list(map(int, list(input())))
count = 0
n = n[::-1] + [0]

for idx, num in enumerate(n):
    if num == 10:
        n[idx+1] += 1
    elif num == 5:
        if n[idx+1] >= 5:
            n[idx+1] += 1
            count += 10 - num
        else:
            count += num

    elif num <= 4:
        count += num
    else:
        count += 10 - num
        n[idx+1] += 1

print(count)

Solution (Python):
def main():
    s = input()
    s = list(reversed(s))
    s.append('0')
    dp = [[10**10 for _ in range(2)] for _ in range(len(s)+1)]
    dp[0][0] = 0
    for i in range(len(s)):
        for j in range(2):
            x = int(s[i])
            x += j
            for a in range(10):
                ni = i+1
                nj = 0
                b = a-x
                if b < 0:
                    nj = 1
                    b += 10
                dp[ni][nj] = min(dp[ni][nj], dp[i][j]+a+b)
    print(dp[len(s)][0])


main()

Solution (Python):

import sys
input = sys.stdin.readline

def main():
    N = [0] + list(map(int, tuple(input().rstrip("\n"))))
    Ncopy = N.copy()
    ans = 0

    flag = False
    for i in range(len(N)-1, 0, -1):
        if (Ncopy[i] <= 4) or (Ncopy[i] == 5 and N[i-1] <= 4):
            ans += Ncopy[i]
            flag = False
        else:
            Ncopy[i-1] += 1
            if not flag:
                ans += 10 - N[i]
            else:
                ans += 9 - N[i]
            Ncopy[i] = 0
            flag = True

    if Ncopy[0] == 1:
        ans += 1

    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
d,e=0,0
for x in list("0"+input()):
	d,e=int(x)+min(e,d),9-int(x)+min(e,d+2)
print(min(d,e))

Solution (Python):
nn = [0] + list(map(int, list(input())))
dp0, dp1 = 0, 0
for i in range(len(nn)):
	dp0, dp1 = nn[i] + min(dp1, dp0), 9 - nn[i] + min(dp1, dp0 + 2)
print(min(dp0, dp1))

Solution (Python):

import sys, math, itertools, collections, bisect
input = lambda: sys.stdin.buffer.readline().rstrip().decode('utf-8')
inf = float('inf') ;mod = 10**9+7
mans = inf ;ans = 0 ;count = 0 ;pro = 1

L=list(map(int,input())); n=len(L)
L.reverse();L.append(0)
for i in range(n):

  if L[i] >= 6:
    count += 10-L[i]
    L[i] = 0; L[i+1] += 1

  elif L[i] == 5 and L[i+1] >= 5:
    count += 10-L[i]
    L[i] = 0; L[i+1] += 1

print(count + sum(L))

Solution (Python):
m=str(raw_input())
n=[int(i) for i in m]
n.insert(0,0)
l=len(n)
ans=0
for i in range(l-1,-1,-1):
    current=n[i]
    if(current<5):
        ans+=current
    elif(current==5):
        ans+=current
        if(n[i-1]>=5):
            n[i-1]+=1
    else:
        ans+=10-current
        n[i-1]+=1
print ans

Solution (Python):
def main():
    n = input()[::-1] + "0"
    s = 0
    cnt = 0
    for i, ni in enumerate(n[:-1]):
        k = int(ni) + s
        if k < 5 or k == 5 and int(n[i + 1]) < 5:
            cnt += k
            s = 0
        else:
            cnt += 10 - k
            s = 1
    cnt += s
    print(cnt)

if __name__ == '__main__':
    main()

Solution (Python):
n = [0] + list(map(int, list(input())))
ans = 0
c_in = 0

while n:
    s = n.pop()
    s += c_in
    if 0 <= s <= 4:
        ans += s
        c_in = 0
    elif 6 <= s:
        ans += abs(10 - s)
        c_in = 1
    else:
        ans += 5
        if 5 <= n[-1]:
            c_in = 1
        else:
            c_in = 0

print(ans)

Solution (Python):
N_str = input()

ln = len(N_str)
ans = 0
no_mu, move_up = int(N_str[-1]), 11 - int(N_str[-1])
for i in range(2, ln + 1):
    n = int(N_str[-i])
    no_mu, move_up = n + min(no_mu, move_up), min(11 - n + no_mu, 9 - n + move_up)
print(min(no_mu, move_up))

Solution (Python):
N = ("00"+input())[::-1]

ans = 0
carry = 0
for i in range(len(N)-1):
    n = int(N[i])
    nextn = int(N[i+1])
    if carry == 1:
        carry = 0
        n += 1

    if n <=4:
        ans += n
    elif n >= 6:
        ans += 10-n
        carry = 1
    else: 
        if nextn <= 4:
            ans += n
        else:
            ans += 10-n
            carry = 1

print(ans)

Solution (Python):
import sys
readline = sys.stdin.readline

def calc(k):
    return 10-k

S = [0] + list(map(int, readline().strip()))

M = len(S)
inf = 10**9+7
dpn = [inf]*M
dpk = [inf]*M
dpn[0] = 0
dpk[0] = 1
pre = 0
for i in range(1, M):
    s = S[i]
    if s != 9:
        dpn[i] = min(dpn[i-1] + s, dpk[i-1] + calc(s))
        dpk[i] = min(dpn[i-1] + s+1, dpk[i-1] + calc(s+1))
        pre = i
    else:
        dpn[i] = min(dpn[i-1] + s, dpk[pre] + calc(s))
        dpk[i] = dpk[pre]

print(dpn[-1])

Solution (Python):
N = input()

nagasa = len(N)
flag = 0
res = 0
for i in range(nagasa):
	s = nagasa - i - 1
	n = int(N[s])

	if flag == 2:
		if n <= 4:
			flag = 0
			res += n
		elif n == 5:
			flag = 1
			res += 4
		elif n >= 6:
			flag = 1
			res += 9 - n
	else:
		if flag == 1:
			n += 1
		if n == 5:
			flag = 2
			res += 5
		elif n > 5:
			flag = 1
			res += 10 - n
		else:
			flag = 0
			res += n

if flag == 1:
	print(res + 1)
else:
	print(res)

Solution (Python):
import sys


def main():
    S = input()
    l = len(S)
    S = "0"+ S
    up = 0
    ans = 0
    for i in range(l):
        num = int(S[-i-1])+up
        if num == 5:
            ans += 5
            if int(S[-i-2]) < 5:
                up = 0
            else:
                up = 1
        elif num > 5:
            ans += 10-num
            up = 1
        else:
            ans += num
            up = 0
            
    print(ans+up)
    
if __name__ == "__main__":
    main()

Solution (Python):


iim = lambda: map(int, input().rstrip().split())

def resolve():
    n = [int(c) for c in "0" + input()]
    I = len(n)
    ans = 0
    for i in range(I-1, -1, -1):
        b = n[i]
        if b < 5:
            ans += b
        elif b == 5:
            c = n[i-1]
            ans += b
            if c >= 5:
                n[i-1] += 1
        else:
            ans += 10 - b
            n[i-1] += 1
    print(ans)

if __name__ == "__main__":
    resolve()

Solution (Python):


iim = lambda: map(int, input().rstrip().split())

def resolve():
    n = [int(c) for c in "0" + input()]
    I = len(n)
    ans = 0
    for i in range(I-1, -1, -1):
        b = n[i]
        if b < 5:
            ans += b
        elif b == 5:
            for j in range(2):
                c = n[i-j-1]
                cn = 5 - j
                if c < cn:
                    ans += b
                    break
                elif c > cn:
                    ans += b
                    n[i-1] += 1
                    break
            else:
                ans += b
                n[i-1] += 1
        else:
            ans += 10 - b
            n[i-1] += 1
    print(ans)

if __name__ == "__main__":
    resolve()

Solution (Python):
N = list(input())
n = [int(val) for val in reversed(N)] + [0]
ln = len(N)

ans = 0
for i in range(ln):
    if n[i] <= 4: a = n[i]
    elif n[i] == 5:
        if n[i+1] <= 4:
            a = n[i]
        else:
            a = 10 - n[i]
            n[i+1] += 1
    else:
        n[i+1] += 1
        a = 10 - n[i]
    ans += a

ans += n[ln]
print(ans)

Solution (Python):

import sys
input = sys.stdin.readline
INF = 10**9

a = [int(item) for item in list(input().rstrip())]
n = len(a)

dp = [[INF] * 2 for _ in range(n + 1)] 
dp[0][0] = 0

for i, item in enumerate(a):
    dp[i+1][0] = min(dp[i+1][0], dp[i][0] + item, dp[i][1] + item)
    dp[i+1][1] = min(dp[i+1][1], dp[i][0] + 10 - item + 1, dp[i][1] + 10 - item - 1)

print(min(dp[n]))

Solution (Python):
def main():
  n=list(input())
  n=[int(i) for i in reversed(n)]
  l=len(n)
  n.append(0)
  
  ans=0
  for i in range(l):
    if n[i]<=4:
      a=n[i]
    elif n[i]==5:
      if n[i+1]<=4:
        a=n[i]
      else:
        a=10-n[i]
        n[i+1]+=1
    else:
      n[i+1]+=1
      a=10-n[i]
    ans+=a
  ans+=n[l]
  print(ans)  
if __name__=='__main__':
    main()

Solution (Python):
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def get_nums_l():
    return [ int(s) for s in input().split(" ")]

def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

s = input()
n = len(s)
ans = 0

dp1 = [999999999999999999] * (n+1)
dp2 = [999999999999999999] * (n+1)


dp1[0] = 0
dp2[0] = 1

for i,c in enumerate(s):
    a = int(c)

    dp1[i+1] = min(dp1[i]+a, dp2[i]+a+1)
    dp2[i+1] = min(dp1[i]+a+1, dp2[i]+(10-a-1), dp2[i]+a+2)

print(min(dp1[n], dp2[n]+1))

Solution (Python):
n = [0]
n1 = list(input())
n2 = [int(s) for s in n1]
nn = len(n1)
n = n + n2


ans = 0
for i in range(nn, -1, -1):
    
    if n[i] >= 10:
        n[i - 1] += 1
    elif n[i] == 5:
        if n[i - 1] >= 5:
            ans += n[i]
            n[i - 1] += 1
        else:
            ans += n[i]
    elif n[i] < 5:
        ans += n[i]
    else:
        ans += 10 - n[i]
        n[i - 1] += 1
print(ans)

Solution (Python):
import sys, bisect, math, itertools, string, queue, copy


from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush

sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) 
def inpm(): return map(int,input().split()) 
def inpl(): return list(map(int, input().split())) 
def inpls(): return list(input().split())  
def inplm(n): return list(int(input()) for _ in range(n)) 
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return sorted([list(map(int, input().split())) for _ in range(n)]) 

def main():
    n = list(input())
    l = len(n)
    ans = 0
    for i in range(l):
        n[i] = int(n[i])
    for i in range(l-1,-1,-1):
        if n[i] <= 4:
            ans += n[i]
        elif n[i] == 5 and (i == 0 or n[i-1] <= 4):
            ans += n[i]
        else:
            ans += 10 - n[i]
            n[i] = 0
            if i != 0:
                n[i-1] += 1
        if i == 0 and n[i] == 0:
            ans += 1
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
s = input(); n = len(s)
dp = [ [0,1<<32] for i in range(n+1) ]
for i in range(n):
  d = ord(s[i])-ord('0')
  dp[i+1][0] = min(dp[i][0], dp[i][1])+d
  dp[i+1][1] = min(dp[i][0], dp[i][1]-2)+11-d
print(min(dp[n][0],dp[n][1]))

Solution (Python):
def main():
  n=list(input())
  n=[int(i) for i in n]
  l=len(n)
  
  dp=[[0]*2 for _ in range(l+1)]
  if n[0]>=5:
    dp[0][1]=1
    
  for i in range(l):
      dp[i+1][0]=min(dp[i][0]+n[i],dp[i][1]+10-n[i])
      dp[i+1][1]=min(dp[i][0]+n[i]+1,dp[i][1]+9-n[i])
      
  
  print(dp[l][0])

if __name__=='__main__':
    main()

Solution (Python):
s = input(); n = len(s); INF=1<<32
dp = [ [0,INF] for i in range(n+1) ]
for i in range(n):
  d = int(s[i])
  dp[i+1][0] = min(dp[i][0], dp[i][1])+d
  dp[i+1][1] = min(dp[i][0], dp[i][1]-2)+11-d
print(min(dp[n][0],dp[n][1]))

Solution (Python):
s = input()
n = len(s)
dp = [ [0,1e18] for i in range(n+1) ]
for i in range(n):
  d = int(s[i])
  dp[i+1][0] = min(dp[i][0], dp[i][1])+d
  dp[i+1][1] = min(dp[i][0], dp[i][1]-2)+11-d
print(min(dp[n][0],dp[n][1]))

Solution (Python):
s = input()
n = len(s)
dp = [ [0,0] for i in range(n) ]
dp[0][0] = int(s[0])
dp[0][1] = 11-int(s[0])
for i in range(n-1):
  d = int(s[i+1])
  dp[i+1][0] = min(dp[i][0]+d, dp[i][1]+d)
  dp[i+1][1] = min(dp[i][0]+11-d, dp[i][1]+9-d)
print(min(dp[n-1][0],dp[n-1][1]))

Solution (Python):
s = input()

s = s[::-1]
s += "0"
l = len(s)

dp = [[float("inf")] * 2 for _ in range(l + 1)]
dp[0][0] = 0

for i, e in enumerate(s):
    for j in range(2):
        x = int(e)
        x += j
        for a in range(10):
            ni = i + 1
            nj = 0
            b = a - x
            if b < 0:
                nj = 1
                b += 10

            dp[ni][nj] = min(dp[ni][nj], dp[i][j] + a + b)

ans = dp[l][0]
print(ans)

Solution (Python):
s = input()
n = len(s)
dp = [ [0,0] for i in range(n) ]
dp[0][0] = ord(s[0])-ord('0')
dp[0][1] = 11-(ord(s[0])-ord('0'))
for i in range(n-1):
  d = ord(s[i+1])-ord('0')
  dp[i+1][0] = min(dp[i][0], dp[i][1]) + d
  dp[i+1][1] = min(dp[i][0]+11-d, dp[i][1]+9-d)
print(min(dp[n-1][0],dp[n-1][1]))

Solution (Python):
N = list(input())
N = list(map(int, N))
N = [0] + N
n = len(N)

answer = 0
for i in range(n - 1, -1, -1):
    j = N[i]
    if j == 10:
        N[i - 1] += 1
        continue
    if j == 5 and N[i - 1] >= 5:
        N[i - 1] += 1
        answer += 5
    elif j <= 5:
        answer += j
    else:
        N[i - 1] += 1
        answer += 10 - j

print(answer)

Solution (Python):
N = list(input())
N = list(map(int, N))
N = [0] + N
n = len(N)

answer = 0
for i in range(n - 1, -1, -1):
    if N[i] == 10:
        N[i - 1] += 1
        continue
    if N[i] == 5 and N[i - 1] >= 5:
        N[i - 1] += 1
        answer += 5
    elif N[i] <= 5:
        answer += N[i]
    else:
        N[i - 1] += 1
        answer += 10 - N[i]

print(answer)

Solution (Python):
s = input()
n = len(s)
dp = [ [0,0] for i in range(n) ]
dp[0][0] = ord(s[0])-ord('0')
dp[0][1] = 11-(ord(s[0])-ord('0'))
for i in range(n-1):
  d = ord(s[i+1])-ord('0')
  dp[i+1][0] = min(dp[i][0], dp[i][1]) + d
  dp[i+1][1] = min(dp[i][0]+11-d, dp[i][1]+9-d)
print(min(dp[n-1][0],dp[n-1][1]))

Solution (Python):
s=input()
l=len(s)
cnt=0
A=[]
A.append(0)
for i in range(l):
  A.append(int(s[i]))
for i in reversed(range(l+1)):
  if A[i]<5 or (A[i]==5 and A[i-1]<5):
    cnt+=A[i]
  else:
    A[i-1]+=1
    cnt+=(10-A[i])
    A[i]=0
print(cnt)

Solution (Python):
if __name__ == "__main__":
    n = '0' + input()

    ans = 0
    flag = 0

    for i in range(len(n)-1, 0, -1):
        if int(n[i]) + flag == 10:
            flag = 1
        elif int(n[i]) + flag > 5 or (int(n[i]) + flag == 5 and int(n[i-1]) > 4):
            ans += 10 - int(n[i]) - flag
            flag = 1
        else:
            ans += int(n[i]) + flag
            flag = 0

    if flag == 1:
        ans += 1

    print(ans)

Solution (Python):
import sys

input = sys.stdin.readline
N = list(map(int, input().strip()))[::-1]
ans = 0
before = 0
L = len(N)
for i, c in enumerate(N):
    n = c + before
    if 0 <= n < 5:
        before = 0
        ans += n
    elif n == 5:
        if i+1 == L:
            before = 0
            ans += n
            continue
        if N[i+1] < 5:
            before = 0
            ans += n
        else:
            ans += 10-n
            before = 1
    else:
        ans += 10-n
        before = 1
print(ans + before)

Solution (Python):
*s,a=map(int,input()+'000')
for i in range(len(s)-1):
  if s[i]>5or s[i]>4<s[i+1]:
    s[i+1]+=1
    a+=10-s[i]
  else:
    a+=s[i]
print(a)

Solution (Python):
*s,a=map(int,input()+'000')
for i in range(len(s)-1):
  if s[i]>5or s[i]>4<s[i+1]:
    s[i+1]+=1
    a+=10-s[i]
  else:
    a+=s[i]
print(a)

Solution (Python):
N = list(map(int, list(input())))
ans = 0

for i in range(len(N) - 1, -1, -1):
    if N[i] > 9:
        if i > 0:
            N[i - 1] += 1
        else:
            ans += 1
    elif N[i] == 5 and i > 0:
        if N[i - 1] >= 5:
            ans += 5
            N[i - 1] += 1
        else:
            ans += N[i]
    elif N[i] < 6:
        ans += N[i]
    else:
        if i > 0:
            N[i - 1] += 1
            ans += 10 - N[i]
        else:
            ans += 10 - N[i] + 1

print(ans)

Solution (Python):
s = input()
l = len(s)
cnt = 0
ls = []
ls.append(0)
ls.append(0)
for i in range(l):
    ls.append(int(s[i]))
for i in range(l+1):
    if 6<= ls[-i-1] or (ls[-i-1] ==5 and ls[-i-2] >=5):
        ls[-i-1] = 10 -ls[-i-1] 
        ls[-i-2] += 1 
print(sum(ls))

Solution (Python):



def main():
    inf = 18 * (10 ** 6 + 1)

    s = '0' + input()
    n = len(s)

    s = map(int, reversed(s))  

    dp = [[inf] * 2 for _ in range(n + 1)]
    dp[0][0] = 0

    for i, c in enumerate(s):  
        for j in range(2):
            x = c + j
            if x != 10:  
                dp[i + 1][0] = min(dp[i + 1][0], dp[i][j] + x)  
            if x != 0:
                dp[i + 1][1] = min(dp[i + 1][1], dp[i][j] + (10 - x))  

    print(dp[n][0])


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    from itertools import islice

    inf = 18 * (10 ** 6 + 1)

    s = '0' + input()
    n = len(s)

    s = map(int, reversed(s))  

    dp = [[inf] * 2 for _ in range(n + 1)]
    dp[0][0] = 0

    for i, c in enumerate(islice(s, 0, n, 1)):
        for j in range(2):
            x = c + j
            if x != 10:  
                dp[i + 1][0] = min(dp[i + 1][0], dp[i][j] + x)  
            if x != 0:
                dp[i + 1][1] = min(dp[i + 1][1], dp[i][j] + (10 - x))  

    print(dp[n][0])


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    from itertools import islice

    inf = 18 * (10 ** 6 + 1)

    s = '0' + input()
    n = len(s)

    s = map(int, reversed(s))  

    dp = [[inf] * 2 for _ in range(n + 1)]
    dp[0][0] = 0

    for i, c in enumerate(islice(s, 0, n, 1)):
        for j in range(2):
            x = c + j
            if x < 10:
                dp[i + 1][0] = min(dp[i + 1][0], dp[i][j] + x)  
            if x > 0:
                dp[i + 1][1] = min(dp[i + 1][1], dp[i][j] + (10 - x))  

    print(dp[n][0])


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    inf = 18 * (10 ** 6 + 1)

    s = input()
    s = '0' + s
    *s, = map(int, s)  

    n = len(s)

    dp = [[inf] * 2 for _ in range(n + 1)]
    dp[0][0] = 0

    for i, c in enumerate(s[::-1]):
        for j in range(2):
            x = c + j
            if x < 10:
                dp[i + 1][0] = min(dp[i + 1][0], dp[i][j] + x)  
            if x > 0:
                dp[i + 1][1] = min(dp[i + 1][1], dp[i][j] + (10 - x))  

    print(dp[n][0])


if __name__ == '__main__':
    main()

Solution (Python):



def main():
    inf = 18 * (10 ** 6 + 1)

    s = input()
    s = '0' + s

    n = len(s)

    dp = [[inf] * 2 for _ in range(n + 1)]
    dp[0][0] = 0

    for i, c in enumerate(s[::-1]):
        for j in range(2):
            x = int(c) + j
            if x < 10:
                dp[i + 1][0] = min(dp[i + 1][0], dp[i][j] + x)  
            if x > 0:
                dp[i + 1][1] = min(dp[i + 1][1], dp[i][j] + (10 - x))  

    print(dp[n][0])


if __name__ == '__main__':
    main()

Solution (Python):
n = list(map(int, input()))+[0]
ans = 0
for i in range(len(n)):
    if n[i] < 5 or (n[i]==5 and n[i+1]<5):
        ans += n[i]
    else:
        ans += 10 - n[i]
        n[i+1] += 1
print(ans)

Solution (Python):
N = '0' + input()
L = len(N)

INF = float('inf')
dp = [[INF] * 2 for _ in range(L + 1)]
dp[0][0] = 0

for i in range(L):
    x = int(N[L - 1 - i])
    for j in range(2):
        for a in range(10):
            b = a - j - x
            temp1 = dp[i][j] + a + (b + 10 * (b < 0))
            temp2 = dp[i + 1][b < 0]
            dp[i + 1][b < 0] = min(temp1, temp2)

print(dp[L][0])

Solution (Python):
Ns = [int(s) for s in input()]
order = len(Ns)

dp_just = [0 for _ in range(order + 1)]
dp_plus = [0 for _ in range(order + 1)]

dp_just[0] = 0
dp_plus[0] = 1

for o in range(order):
  n = Ns[o]
  dp_just[o+1] = min(dp_just[o] + n, dp_plus[o] + (10 - n))
  dp_plus[o+1] = min(dp_just[o] + n + 1, dp_plus[o] + (9 -n))
  
print(dp_just[-1])

Solution (Python):
S=input()
N=len(S)
INF=10**9

dp=[[INF for _ in range(2)] for __  in range(N+1)]
dp[0][0]=0
for i in range(N):
    n=int(S[N-1-i])
    ni=i+1
    for j in range(2):
        if n+j<=9:
            dp[ni][0]=min(dp[ni][0],dp[i][j]+n+j)
            dp[ni][1]=min(dp[ni][1],dp[i][j]+10-n-j)
        else:
            dp[ni][1]=min(dp[ni][1],dp[i][j])
print(min(dp[N][0],dp[N][1]+1))

Solution (Python):
n = input()

c = 0
r = 1
for x in map(int, n):
    tc = min(c + x, r + 10 - x)
    if x == 9:
        tr = r
    else:
        tr = min(c + x + 1, r + 10 - (x + 1))
    c, r = tc, tr

print(c)

Solution (Python):
import sys

ns = sys.stdin.readline().strip()
ns = ns[::-1]
ns += '0'
ns_arr = list(ns)
n_arr = [int(s) for s in ns_arr]
nl = len(n_arr)

dp = [[float('inf')] * (nl+1) for _ in range(2)]

dp[0][0] = 0

for j in range(nl):
    for i in range(2):
        num = n_arr[j]
        num += i

        if num < 10:
            dp[0][j+1] = min(dp[0][j+1], dp[i][j] + num)

        if num > 0:
            dp[1][j+1] = min(dp[1][j+1], dp[i][j] + (10 - num))

ans = dp[0][nl]
print(ans)

Solution (Python):
N = input()
A = [int(N[i]) for i in range(len(N))]
A.reverse()
A.append(0)

ans = 0

for i in range(len(A)):
    if A[i] > 5 or (A[i] == 5 and A[i+1] >= 5):
        ans = ans + (10 - A[i])
        A[i+1] = A[i+1] + 1
    else:
        ans = ans + A[i]

print(ans)

Solution (Python):
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)

def get_nums_l():
    return [ int(s) for s in input().split(" ")]

def get_nums_n(n):
    return [ int(input()) for _ in range(n)]

def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

s = input()
n = len(s)
ans = 0

dp1 = [999999999999999999] * (n+1)
dp2 = [999999999999999999] * (n+1)


dp1[0] = 0
dp2[0] = 1

for i,c in enumerate(s):
    a = int(c)

    dp1[i+1] = min(dp1[i]+a, dp2[i]+a+1)
    dp2[i+1] = min(dp1[i]+a+1, dp2[i]+(10-a-1), dp2[i]+a+2)

print(min(dp1[n], dp2[n]+1))

Solution (Python):
S=input()
B0=int(S[-1])
B1=10-int(S[-1])
for s in S[::-1][1:]:
    x=int(s)
    B0,B1=min(B0+x,B1+x+1),min(B0+(10-x),B1+(10-x-1))
print(min(B0,B1+1))

Solution (Python):
import math
from functools import reduce
from collections import deque
import sys
sys.setrecursionlimit(10**7)


def get_nums_l():
    return [ int(s) for s in input().split(" ")]


def get_nums_n(n):
    return [ int(input()) for _ in range(n)]


def get_all_int():
    return map(int, open(0).read().split())

def log(*args):
    print("DEBUG:", *args, file=sys.stderr)

s = input()
n = len(s)
ans = 0

dp1 = [999999999999999999] * (n+1)
dp2 = [999999999999999999] * (n+1)




dp1[0] = 0
dp2[0] = 1

for i,c in enumerate(s):
    a = int(c)

    dp1[i+1] = min(dp1[i]+a, dp2[i]+a+1)
    dp2[i+1] = min(dp1[i]+a+1, dp2[i]+(10-a-1), dp2[i]+a+2)

print(min(dp1[n], dp2[n]+1))

Solution (Python):
def main():
    N=input()
    X=len(N)
    INF=10**100
    dp=[[INF,INF] for i in range(0,X+1)]
    dp[0][0]=0
    dp[0][1]=1
    for j in range(1,X+1):
        dp[j][0]=min(dp[j-1][0]+int(N[j-1])%10,dp[j-1][1]+10-int(N[j-1])%10)
        if int(N[j-1])%10!=9:
            dp[j][1]=min(dp[j-1][1]+9-int(N[j-1])%10,dp[j-1][0]+int(N[j-1])%10+1)
        else:
            dp[j][1]=dp[j-1][1]+9-int(N[j-1])%10
    print(dp[X][0])

if __name__ == '__main__':
    main()

Solution (Python):
X = [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
def solve(N):
    N = [int(c) for c in N][::-1]
    p = 0
    b = 0
    for i in range(len(N)):
        c = N[i] + b
        p += X[c]
        if c == 5:
            b = 0 if i == len(N)-1 or N[i+1] < 5 else 1
        else:
            b = c > 5
    return p + b

print(solve(input()))

Solution (Python):
s=input()
a=0
b=0
c=len(s)
s='0'+s
s=s[::-1]
d=0
for i in range(c+1):
  if 0<b:
    if 4<int(s[i])+1:
      if 5==int(s[i])+1 and int(s[i+1])<5:
        a+=5
        b=0
      else:
        a+=(9-int(s[i]))
    else:
      a+=(int(s[i])+1)
      b=0
  else:
    if 4<int(s[i]):
      if int(s[i])==5 and int(s[i+1])<5:
        a+=5
      else:
        b+=1
        a+=(10-int(s[i]))
    else:
      a+=int(s[i])
print(a)