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):
import sys
input = sys.stdin.readline

Num_str = list(input().rstrip())
L = len(Num_str)
Num = []

for n in reversed(Num_str):
    Num.append(int(n))

S = 0
up = False
for i, n in enumerate(Num):
    if up:
        n += 1
    if n < 5:
        S += n
        up = False
    elif n == 5:
        S += 5
        up = (i != L-1 and Num[i+1] >= 5)
    else:
        S += 10 - n
        up = True
if up:
    S += 1
print(S)

Solution (Python):
S = input()
dp = [0, 1]
for s in S:
    i = int(s)
    a = min(dp[0] + i,   dp[1] + 10 - i)
    b = min(dp[0] + i+1, dp[1] + 10 - (i+1))
    dp = [a, b]
    
print(dp[0])

Solution (Python):
n = reversed(list(map(int, input())))
a, b = 0, 30
for x in n:
    a, b = min(a+x, b+x), min(a-x+11, b-x+9)
print(min(a, b))

Solution (Python):
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
mod=pow(10,9)+7

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




dp0=[float('inf')]*(keta+1)
dp1=[float('inf')]*(keta+1)
dp0[0]=0


for i in range(keta):
    s=int(n[-1-i])
    dp0[i+1]=min(dp0[i]+s,dp1[i]+s+1)
    dp1[i+1]=min(dp0[i]+(10-s),dp1[i]+(10-s-1))

print(min(dp0[-1],dp1[-1]+1))

Solution (Python):
def main():
    s = input().strip()
    carry = 0
    result = 0
    for i in range(len(s) - 1, -1, -1):
        carry, x = divmod(ord(s[i]) - ord("0") + carry, 10)
        if x > 5 or (x == 5 and i > 0 and s[i - 1] >= "5"):
            carry += 1
            result += 10 - x
        else:
            result += x
    result += carry
    print(result)


main()

Solution (Python):
l = list(map(int,input()))


l.reverse()
l.append(0)

l_copy = l.copy()

N = len(l)

pay = []
for i in range(N):
    if l[i] == 5 and l[i+1]>4:
        pay.append(0)
        l[i+1] += 1
    elif l[i] <= 5:
        pay.append(l[i])
    elif 10 > l[i] > 5:
        pay.append(0)
        l[i+1] += 1
    elif l[i] == 10:
        pay.append(0)
        l[i+1] += 1

pay_copy = pay.copy()

remain = []
for i in range(N):
    k = pay[i] - l_copy[i]
    if  k >= 0:
        remain.append(k)
    else:
        remain.append(k+10)
        pay[i+1] -= 1

result = 0
for i in pay_copy:
    result += i
for i in remain:
    result += i

print(result)

Solution (Python):

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

N = [0 for i in range(l)]

for i in range(l):
    N[i] = int(s[-i-1])
N.append(0)

for i in range(l+1):
    if N[i]<5:
        ans += N[i]
    elif N[i]>5:
        ans += 10-N[i]
        N[i+1] += 1
    elif N[i+1]>4:
        ans += 10-N[i]
        N[i+1] += 1
    else:
        ans += N[i]

print(ans)

Solution (Python):
n = ["0"] + list(input())
n = n[::-1]
ans = 1

for i in range(len(n)):
    n[i] = int(n[i])

dp = [[0] * 2 for i in range(len(n) + 1)]
dp[0][1] = 1
for i in range(len(n)):
    dp[i + 1][0] = min(dp[i][0] + n[i], dp[i][1] + n[i] + 1)
    dp[i + 1][1] = min(dp[i][0] + 10 - n[i], dp[i][1] + 10 - (n[i] + 1))

print(min(dp[-1]))

Solution (Python):
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
mod=pow(10,9)+7

n=input()





keta=len(n)
ans=0



dp=[[0,1]]
for i in range(keta):
    dp.append([float('inf')]*2)


for i in range(keta):
    s=int(n[-1-i])
    dp[i+1][0]=min(dp[i][0]+s,dp[i][1]+s+1)
    dp[i+1][1]=min(dp[i][0]+(10-s),dp[i][1]+(10-s-1))

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

Solution (Python):
n = list(input())
n.insert(0, '0')

ans = 0
for i in range(len(n)-1, -1, -1):
    if n[i] == '0':
        pass
    elif int(n[i]) <= 4:
        ans += int(n[i])
    elif int(n[i]) == 5 and int(n[i-1]) <= 4:
        ans += int(n[i])
    else:
        ans += 10 - int(n[i])
        n[i-1] = str(int(n[i-1]) + 1)

print(ans)

Solution (Python):
N = list(map(int,list(input())))
ans = 0
skfl = 0
nf = 0
for i in range(1, len(N) + 1):
    if i != len(N):
        if N[-(i+1)] >= 5:
            nf = 1
    if N[-i] + skfl + nf > 5:
        ans += 10 - N[-i] - skfl
        skfl = 1
    else:
        ans += N[-i] + skfl
        skfl = 0
    nf = 0
print(ans+skfl)

Solution (Python):
N = tuple(input())
N = tuple(map(int, N))

ans = 0
flag = False
flag5 = False
i = len(N)-1


for x in reversed(N):
    if flag or (flag5 and x >= 5):
        x += 1
    flag5 = False
    flag = False
    if x > 5:
        ans += (10 - x)
        flag = True
        if i == 0:
            ans += 1
    else:

        ans += x
    if x == 5:
        flag5 = True
    i -= 1

print(ans)

Solution (Python):
N = tuple(input())
N = tuple(map(int, N))

ans = 0
flag = False
flag5 = False
i = len(N)-1


for x in reversed(N):
    if flag or (flag5 and x >= 5):
        x += 1
    flag5 = False
    flag = False
    if x > 5:
        ans += (10 - x)
        flag = True
        if i == 0:
            ans += 1
    else:

        ans += x
    if x == 5:
        flag5 = True
    i -= 1

print(ans)

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

N = readline().rstrip()
N = list(map(int, N))
L = len(N)

total = 0

for i in range(L - 1, -1, -1):
    k = N[i]
    if k <= 4:
        total += k
    elif k >= 6:
        total += 10 - k
        if i == 0:
            total += 1
        else:
            N[i - 1] += 1
    else:
        if i == 0:
            total += k
        else:
            if N[i - 1] <= 4:
                total += k
            else:
                total += 10 - k
                N[i - 1] += 1

print(total)

Solution (Python):
n = list(map(int, reversed(list(input()))))
a , b = 0, 9999
for x in n:
    a, b = min(a+x, b+x), min(a+10-x+1, b+10-x-1)
print(min(a, b))

Solution (Python):
import sys


TEST_INPUT = [
    """
    36
    """,
    """
    91
    """,
    """
    314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170
    """
]
ANSWER = [
    "8",
    "3",
    "243"
]


class InputHandler:

    def __init__(self, text_lines="", is_test=False):
        self.data = list(text_lines.split("\n"))
        self.index = 0
        self.is_test = is_test

    def input(self):
        if self.is_test:
            self.index += 1
            return self.data[self.index].strip()
        else:
            return sys.stdin.readline().rstrip()


def solve(n):

    dp = [0, 1]
    for s in n:
        a = int(s)
        dp = [min(dp[0] + a, dp[1] + 10 - a), min(dp[0] + a + 1, dp[1] + 9 - a)]

    return dp[0]


def input_and_solve(ih):
    n = ih.input()
    res = solve(n)
    return res


def main():
    ih = InputHandler()
    res = input_and_solve(ih)
    print(res)


def test():
    for test_input, ans in zip(TEST_INPUT, ANSWER):
        ih = InputHandler(test_input, True)
        res = input_and_solve(ih)
        
        assert str(res) == str(ans)


if __name__ == "__main__":
    test()
    main()

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[l][0],dp[l][1]+1))

Solution (Python):
NN = 2020202
MOD = 10**9+7
INF = float("inf")

A = input()
N = [0]*len(A)
for i in range(len(A)):
    N[i] = int(A[i])
N = N[::-1]
N.append(0)
kyaku = 0
mise = 0

for i in range(len(N)-1):
    
    if N[i] == 5 and N[i+1] >= 5:
        mise += 10 - N[i]
        N[i+1] += 1
    elif N[i] <= 5:
        kyaku += N[i]
    else:
        mise += 10-N[i]
        N[i + 1] += 1

if N[-1] == 1:
    kyaku += 1

print(kyaku+mise)

Solution (Python):
N = input()
rN = N[::-1]

res = 0
add = False

for i, n in enumerate(rN):
    p = int(n)
    if add:
        p += 1
    if p == 10:
        continue
    elif p == 5:
        if len(N) > i+1 and int(rN[i+1]) >= 5:
            add = True
            res += p
        else:
            add = False
            res += p
    elif p < 5:
        add = False
        res += p
    else:
        add = True
        res += 10-p

if add:
    res += 1

print(res)

Solution (Python):
N = input()

keta = len(N)


N_list = [0] * (keta+1)
ans_num = 0

for i in reversed(range(keta)):
    N_list[keta-i-1] = int(N[i])

for i in range(keta+1):
    if N_list[i] == 5 and N_list[i+1] >= 5:
        
        N_list[i+1] += 1
        ans_num += 10 - N_list[i]
    elif N_list[i] > 5:
        
        N_list[i+1] += 1
        ans_num += 10 - N_list[i]
    else:
        
        ans_num += N_list[i]

print(ans_num)

Solution (Python):
s =list(map(int, list(input())))
INF = 1001001001001
dp1=[INF]*1001001
dp2=[INF]*1001001
n=len(s)
dp1[n-1]=s[n-1]
dp2[n-1]=10-s[n-1]
for i in reversed(range(n-1)):
    if s[i]<9:
        dp1[i] = min(dp1[i+1]+s[i],dp2[i+1]+s[i]+1)
    else:
        dp1[i] = dp1[i+1]+s[i]
    dp2[i] = min(dp1[i+1]+10-s[i], dp2[i+1]+10-s[i]-1)

dp2[0]+=1
print(min(dp1[0], dp2[0]))

Solution (Python):
n = input()
m = len(n)
dp0 = [0]*m
dp1 = [0]*m
dp1[0] = min(int(n[0])+2,11-int(n[0]))
dp0[0] = int(n[0])
for i in range(1,m):
    dp0[i] = min(dp0[i-1],dp1[i-1]) + int(n[i])
    if int(n[i]) != 9:
        dp1[i] = min(dp0[i-1]+int(n[i])+2,dp1[i-1]+min(int(n[i])+2,9-int(n[i])))
    else:
        dp1[i] = dp1[i-1]
print(min(dp0[m-1],dp1[m-1]))

Solution (Python):
def main():
  s=input()
  
  
  
  
  lens=len(s)

  d=int(s[0])
  p=11-int(s[0])

  for c in s[1:]:
      j=int(c)
      a=min(d+j,p+j)
      b=min(d+11-j,p+9-j)
      d,p=a,b

  print(min(d,p))

if __name__ == '__main__':
    main()

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline

    S_raw = input().rstrip('\n')

    S = [int(s) for s in S_raw]
    N = len(S)
    ans = 0
    dp0 = [0] * (N+1)
    dp1 = [0] * (N+1)
    dp1[0] = 1
    for i in range(N):
        s = S[i]
        dp0[i+1] = min(dp0[i] + s, dp1[i] + s+1)
        dp1[i+1] = min(dp1[i] + min(s+2, 9-s), dp0[i] + 1 + min(s, 10-s))
    print(min(dp0[-1], dp1[-1]+1))


if __name__ == '__main__':
    main()

Solution (Python):
N = list(map(int, list(input())))
N.reverse()
N.append(0)
res = 0
f = False
for i in range(len(N)-1):
    n = N[i]
    if n < 5:
        res += n
    else:
        if n == 5:
            if N[i+1] >= 5:
                N[i+1] += 1
        else:
            N[i+1] += 1
        res += 10-n

if N[-1] > 0:
    res += 1

print(res)

Solution (Python):
n = input()

dp = [[0] * 2 for _ in range(2)]

digit = int(n[-1])

dp[0][0] = 10 - digit
dp[0][1] = digit

for i in range(1, len(n) + 1):
    if i == len(n):
        digit = 0
    else:
        digit = int(n[-i-1])

    if i % 2 == 0:
        dp[0][0] = min(dp[1][0] + 10 - digit - 1, dp[1][1] + 10 - digit)
        dp[0][1] = min(dp[1][0] + digit + 1, dp[1][1] + digit)
    else:
        dp[1][0] = min(dp[0][0] + 10 - digit - 1, dp[0][1] + 10 - digit)
        dp[1][1] = min(dp[0][0] + digit + 1, dp[0][1] + digit)


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

Solution (Python):


P = [0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
C = [0, 0, 0, 0, 0, 5, 4, 3, 2, 1]
X = [0, 1, 2, 3, 4, 5, 4, 3, 2, 1]
import sys
def solve(N):
    N = [int(c) for c in N]
    N = N[::-1]
    p = 0
    b = 0
    s = []
    for i in range(len(N)):
        c = N[i]
        c += b
        if c == 10:
            c = 0
            b = 1
            p += X[c]
            
        elif c == 5:
            if i == len(N)-1:
                p += 5
                
                b = 0
            else:
                if N[i+1] < 5:
                    p += 5
                    b = 0
                    
                else:
                    p += 5    
                    b = 1
                    
        elif c > 5:
            b = 1
            p += X[c]
            
        else:
            b = 0
            p += X[c]
            
    if b:
        s.append(b)
        pass
    
    return p + b, s[::-1]

def count(n):
    return sum([int(x) for x in str(n)])

def test(N):
    m = 10e10
    p = 0
    for P in range(N, N*10):
        n = count(P) + count(P - N)
        if n < m:
            p = P
            m = n
    e,s = solve(str(N))
    if e != m:
        print("N=%d"%N, "expected=%d"%m, p, "actual=%d"%e, "".join(str(c) for c in s))

N = [int(x) for x in input()]
a,_ = solve(N)
print(a)
if 1==0:
    for i in range(1, 1000):
        test(i)
    test(159)
    test(149)
    test(449)
    test(959)
    test(949)
    test(939)
    test(539)
    test(569)

Solution (Python):
n = input()

dp = [[0] * 2 for _ in range(2)]

digit = int(n[-1])

dp[0][0] = 10 - digit
dp[0][1] = digit

for i in range(1, len(n) + 1):
    if i == len(n):
        digit = 0
    else:
        digit = int(n[-i-1])

    if i % 2 == 0:
        dp[0][0] = min(dp[1][0] + 10 - digit - 1, dp[1][1] + 10 - digit)
        dp[0][1] = min(dp[1][0] + digit + 1, dp[1][1] + digit)
    else:
        dp[1][0] = min(dp[0][0] + 10 - digit - 1, dp[0][1] + 10 - digit)
        dp[1][1] = min(dp[0][0] + digit + 1, dp[0][1] + digit)


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

Solution (Python):
n=input()


count_1=0
count_2=0

p1_1=[0]*len(n)
p1_2=[0]*len(n)
p2_1=[0]*len(n)
p2_2=[0]*len(n)
i=0
p1_1[i]=1
p1_2[i]=10-int(n[i])
p2_1[i]=int(n[i])
p2_2[i]=0

c_1=p1_1[i]+p1_2[i]
c_2=p2_1[i]+p2_2[i]

for i in range(1,len(n)):
    p1_1[i]=1
    p1_2[i]=10-int(n[i])
    p2_1[i]=int(n[i])
    p2_2[i]=0
    
    tmp_c_1 = min([c_2,c_1-2])+(p1_1[i]+p1_2[i])
    tmp_c_2 = min([c_1,c_2])+(p2_1[i]+p2_2[i])
    c_1=tmp_c_1
    c_2=tmp_c_2

print(min([c_1,c_2]))

Solution (Python):
import sys

def solve():
    N = str(input())
    dig = len(N)
    ans = 0
    up = False
    for i in reversed(range(dig)):
        n = int(N[i])
        if 0 <= n <= 4: 
            if up: 
                ans += n + 1
                up = False
                if n == 4:
                    if i > 0:
                        if int(N[i-1]) >= 5: up = True
            else: 
                ans += n 
                up = False
        elif n == 5:
            if up: ans += 4
            else: 
                ans += 5
                if i > 0:
                    if int(N[i-1]) >= 5: up = True
        else: 
            if up: ans += 9 - n
            else: ans += 10 - n
            up = True
        
    if up: ans += 1
    print(ans)

    return 0

if __name__ == "__main__":
    solve()

Solution (Python):






n = input()

flag = 0
count = 0
for i in range(len(n) - 1, -1, -1):
    c = n[i]
    v = int(c) + flag

    if v == 10:
        v = 0
        flag = 1
    else:
        flag = 0
    if v < 5:
        count += v
    elif v == 5:
        if i != 0 and int(n[i-1]) >= 5:
            flag = 1
        count += 5
    else:
        count += 10 - v
        flag = 1
print(count + flag)

Solution (Python):


a = list(input())

ans = 0
next = 0

a.reverse()
a.append('0')

for i in range(len(a)-1):
  num = int(a[i]) + next
  nextnum = int(a[i+1])
  if num <= 4:
    ans += num
    next = 0
  elif num == 5 and nextnum <=4:
    ans += num
    next = 0
  else:
    ans += 10-num
    next = 1
    
if next == 1:
  ans += 1

print(ans)

Solution (Python):
n = input()
n = n[::-1]
l = len(n)
ans = 0
flg = 0
x = []
for j in range(l):
  i = n[j]
  i = int(i)
  if i+flg>=6:
    i += flg
    ans += (10-i)
    flg = 1
  elif i+flg == 5:
    if j == l-1:
      ans += i+flg
      flg = 0
    elif int(n[j+1]) >= 5:
      i += flg
      ans += (10-i)
      flg = 1
    else:
      ans += i+flg
      flg = 0
  else:
    i += flg
    ans += i
    flg = 0
if flg:
  ans += 1
print(ans)

Solution (Python):
kuri_now = False
cost = [0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0]
kuri = [0, 0, 0, 0, 0, 0.5, 1, 1, 1, 1, 1]
result = 0
for digit in input():
    digit = int(digit)
    if kuri_now == 0:
        result += cost[digit]
        kuri_now = kuri[digit]
    elif kuri_now == 1:
        result += cost[digit + 1]
        kuri_now = kuri[digit + 1]
    else:
        if cost[digit] <= cost[digit + 1]:
            result += cost[digit]
            kuri_now = kuri[digit]
        else:
            result += cost[digit + 1]
            kuri_now = kuri[digit + 1]
if kuri_now == 1:
    result += 1
print(result)

Solution (Python):

"""
Created on Sun Feb 16 21:44:28 2020

@author: H_Hoshigi
"""

N = input()

n_list = []
for i in range(len(N)):
    n_list.append(int(N[-(i+1)]))
n_list.append(0)

counter = 0
for i in range(len(N)+1):
    if (n_list[i]<=4) or ((n_list[i]==5)and(n_list[i+1]<=4)):
        counter += n_list[i]
        n_list[i] = 0
    else:
        counter += 10-n_list[i]
        n_list[i] = 0
        n_list[i+1] += 1
    
    

print(counter)

Solution (Python):
s =list(map(int, list(input())))
INF = 1001001001001
dp1=[INF]*1001001
dp2=[INF]*1001001
n=len(s)
dp1[n-1]=s[n-1]
dp2[n-1]=10-s[n-1]
for i in reversed(range(n-1)):
    if s[i]<9:
        dp1[i] = min(dp1[i+1]+s[i],dp2[i+1]+s[i]+1)
    dp2[i] = min(dp1[i+1]+10-s[i], dp2[i+1]+10-s[i]-1)
    
dp2[0]+=1
print(min(dp1[0], dp2[0]))

Solution (Python):
class Solution:

    def solve(self, N: str) -> int:

        L = len(N)
        D = []
        for l in range(L-1, -1, -1):
            D.append(int(N[l]))

        D.append(0)

        ans = 0
        for l in range(L+1):

            
            if D[l] == 10:
                D[l+1] += 1
                D[l] = 0

            if D[l] < 5:
                ans += D[l]
            elif D[l] == 5:
                if D[l+1] >= 5:
                    D[l+1] += 1
                ans += 5
            else:
                ans += 10-D[l]
                D[l+1] += 1



        return ans


if __name__ == '__main__':

    
    N = input()

    
    solution = Solution()
    print(solution.solve(N))

Solution (Python):
n=list(input())
for i in range(len(n)):
  n[i]=int(n[i])
n.reverse()
n.append(0)
ans=0
l=[]
for i in range(len(n)-1):
  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
ans+=n[-1]
print(ans)

Solution (Python):
n = list(input())
r = list(map(int,n))[::-1]
ans = 0
k = 0
f = 0
for i in r:
  i += k
  if f==5 and i>4:
    i += 1
  ans += min(i,10-i)
  k = int(i>5)
  f = i
print(ans+k)

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    N=list(input())
    N=list(reversed(list(map(int,N))))+[0]
    ans=0
    for i in range(len(N)):
        if N[i]>=6 or (N[i]==5 and N[i+1]>=5):
            ans+=10-N[i]
            N[i+1]+=1
        else:
            ans+=N[i]
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
sN = input()

sN_list = [int(d) for d in sN]

ans = 0

carry = 0

Nlen = len(sN)

for i in range(Nlen):
  d = sN_list[Nlen-i-1]
  if i != Nlen-1:
    left = sN_list[Nlen-i-2]
  else:
    left = 0
  if carry == 0:
    if d <= 4:
      ans += d
      carry = 0
    else:
      if d == 5 and left <= 4:
        ans += 5
        carry = 0
        continue
      ans += 10 - d
      carry = 1
  elif carry == 1:
    if carry + d <= 4:
      ans += carry + d
      carry = 0
    else:
      if carry + d == 5 and left <= 4:
        ans += 5
        carry = 0
        continue
      ans += 10 - (carry + d)
      carry = 1
if carry == 1:
  ans += 1

print(ans)

Solution (Python):
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7



N = sys.stdin.buffer.readline().decode().rstrip()

S = []
T = []
for c in N:
    S.append(int(c))
    T.append(9 - int(c))
T[-1] += 1
i = len(T) - 1
while T[i] == 10:
    T[i] = 0
    T[i - 1] += 1
    i -= 1

N = len(S)



dp = [[IINF, IINF] for _ in range(N + 1)]
dp[0][0] = 0
dp[0][0] = 0
for i in range(N):
    
    dp[i + 1][0] = min(dp[i][0] + S[i], dp[i][1] + 1 + S[i])
    dp[i + 1][1] = min(dp[i][1] + T[i], dp[i][0] + 1 + T[i])

print(min(dp[-1]))

Solution (Python):
n = '0' + input()
l = len(n) - 1
n = n[::-1]
cnt = 0
num = 0
now = 0

for x in range(l):
    now = int(n[x]) + num
    num = now // 10
    now %= 10

    if now == 5 and int(n[x + 1]) >= 5:
        cnt += (10 - now)
        num += 1
    elif now <= 5:
        cnt += now
    else:
        cnt += (10 - now)
        num += 1

print(cnt + num)

Solution (Python):
s = input()
s = s[::-1] + '0'

ans = 0
up = 0
for i in range(len(s)):
    int_s = int(s[i])
    if int_s+up <= 4:
        ans += int_s + up
        up = 0
    elif int_s+up == 5:
        if int(s[i+1]) < 5:
            ans += int_s + up
            up = 0
        else:
            ans += 10 - (int_s + up)
            up = 1
    else:
        ans += 10 - (int_s + up)
        up = 1
print(ans)

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    S=[int(s) for s in ST()[::-1]]
    T=S.copy()
    ans = 0
    flag = False
    for i,s in enumerate(S):
        t=S[i]
        if t>=10:
            try:
                S[i+1]+=1
            except:
                flag = True
            t-=10
        if t>5:
            ans += 10-t
            try:
                S[i+1]=(S[i+1]+1)
            except:
                flag = True
        elif t!=5:
            ans += t
        else: 
            ans += t
            try:
                if S[i+1]>=5:
                    S[i+1] += 1
            except:
                pass
    print(ans+int(flag))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
    return sys.stdin.readline()[:-1]
mod=pow(10,9)+7

n=input()
lst=[]
for i in range(len(n)):
    lst.append(int(n[i]))


keta=len(lst)
ans=0
lst.reverse()


dp=[]
for i in range(keta+1):
    dp.append([float('inf')]*2)
dp[0]=[0,1]

for i in range(keta):
    dp[i+1][0]=min(dp[i][0]+lst[i],dp[i][1]+lst[i]+1)
    dp[i+1][1]=min(dp[i][0]+(10-lst[i]),dp[i][1]+(10-lst[i]-1))

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

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

S = input()
S = S[::-1]
N = len(S)

dp0 = [INF] * (N+1)
dp1 = [INF] * (N+1)
dp0[0] = 0
for i, s in enumerate(S):
    s = int(s)
    dp0[i+1] = min(dp0[i+1], dp0[i] + s)
    dp1[i+1] = min(dp1[i+1], dp0[i] + 10-s)
    dp0[i+1] = min(dp0[i+1], dp1[i] + (s+1))
    dp1[i+1] = min(dp1[i+1], dp1[i] + 10-(s+1))
ans = min(dp0[N], dp1[N]+1)
print(ans)

Solution (Python):
import sys

stdin = sys.stdin

ns = lambda: stdin.readline().rstrip()
ni = lambda: int(stdin.readline().rstrip())
nm = lambda: map(int, stdin.readline().split())
nl = lambda: list(map(int, stdin.readline().split()))

s = list(map(int, list(input())))[::-1] + [0]*2
n = len(s) - 1
cnt = 0
fl = 0
for i in range(n+1):
    if s[i] > 5 or (s[i] == 5 and s[i+1] >= 5):
        cnt += 10 - s[i]
        s[i+1] += 1
    else:
        cnt += s[i]

print(cnt)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N):
    ans = 0
    M = N
    M = [c for c in M[::-1]]
    A = []
    M.append('0')
    carry = 0
    for i, c in enumerate(M):
        c = int(c) + carry
        carry = 0
        if c == 5 and int(M[i+1]) >= 5:
                carry += 1
                a = 0
        elif c >= 6:
            carry += 1
            a = 0
        else:
            a = c
        
        A.append(a)
    
    if carry != 0:
        A.append(carry)
    if A[-1] == 0:
        A.pop()
    A = ''.join(map(str, [c for c in A[::-1]]))

    if len(A) - len(N) > 0:
        N = ('0' * (len(A) - len(N))) + N

    carry = 0
    ans = 0
    for a, n in reversed(list(zip(A, N))):
        
        a = int(a)
        ans += a
        n = int(n)
        if carry != 0:
            if a == 0:
                a = 9
                carry =1
            else:
                a -= 1
                carry = 0
        b = a - n
        if b < 0:
            b += 10
            carry = 1
        ans += b

    
    
    
    
    
    
    

    
    return ans


def main():
    N = read_str()
    print(slv(N))


if __name__ == '__main__':
    main()

Solution (Python):
def main():
  s=input()
  
  
  
  
  lens=len(s)

  d=int(s[0])
  p=11-int(s[0])

  for c in s[1:]:
      j=int(c)
      a=min(d+j,p+j)
      b=min(d+11-j,p+9-j)
      d,p=a,b

  print(min(d,p))

if __name__ == '__main__':
    main()

Solution (Python):
def solve_dp(s):
    n = len(s)
    s = [int(c) for c in s]
    inf = 10**9

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

    d0 = s[0]
    dp[0][0] = d0
    dp[0][1] = d0+1

    for i in range(1, n):
        for j in range(2):
            d = s[i] + j
            for k in range(10):
                if d + k >= 10:
                    dp[i][j] = min(dp[i][j], dp[i-1][1] + 2*k + d - 10)
                else:
                    dp[i][j] = min(dp[i][j], dp[i-1][0] + 2*k + d)

    return dp[n-1][0]

if __name__ == '__main__':
    s = input()
    s = "0"+ s
    print(solve_dp(s))

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

n = input().split()[0]

le = len(n)

po = 0

co = 0

for i in range(le-1,-1,-1):
    nu = int(n[i])
    nu += co
    if nu == 5:
        if i != 0 and int(n[i-1]) + 1 > 5:
            co = 1
        else:
            co = 0
        po += nu
    elif nu > 5:
        co = 1
        po += 10 - nu
    else:
        co = 0
        po += nu
print(po + co)

Solution (Python):
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    N=list(input())
    N=list(reversed(list(map(int,N))))+[0]
    ans=0
    for i in range(len(N)):
        if N[i]>=6 or (N[i]==5 and N[i+1]>=5):
            ans+=10-N[i]
            N[i+1]+=1
        else:
            ans+=N[i]
    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
n = input()
n = n[::-1]
kuriage = 0
sum = 0
for i in range(len(n)):
  intI = int(n[i]) + kuriage
  if intI < 5:
    kuriage = 0
    sum += intI
  elif intI > 5:
    kuriage = 1
    sum += (10 - intI)
  else: 
    if len(n) != i+1 and int(n[i+1]) >= 5:
      kuriage = 1
      sum += (10 - intI)
    else:
      kuriage = 0
      sum += intI  
print(sum + kuriage)