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



Sample input:
36


Sample output:
8

Submission status: Accepted

Solution code:
S = input()

ans=0
num = [int(i) for i in S]
num.reverse()

def judge(keta):
    if keta >= len(S):
        return true
    tmp = num[keta]
    if tmp < 5:
        return false
    elif tmp > 5:
        num[keta] = 10 - num[keta]
        num[keta+1] += 1
        return true
    else:
        if judge(keta):
            pass
        
for i in range(len(S)-1):
    tmp = num[i]
    if tmp < 5:
        pass
    elif tmp > 5:
        num[i] = 10-num[i]
        num[i+1] +=1
    else:
        if num[i+1] >= 5:
            num[i] = 10-num[i]
            num[i+1] +=1
        else:
            pass

last = len(S)-1
ans = 0
if num[last] > 5:
    num[last] = 10 - num[last]
    ans =1
print(sum(num)+ans)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline

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

total = 0

a = [0] * L

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

print(total)

Submission status: Accepted

Solution code:
n = input()
digit = [int(n[-(i + 1)]) for i in range(len(n))]
digit.append(0)

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

print(ans)

Submission status: Accepted

Solution code:
N = list(map(int, list(input())))[::-1]
kuriage, up5, ans = False, False, 0

for i in range(len(N)):
    if up5:
        if N[i] < 5:
            ans += N[i] + 5
        else:
            ans += 14 - N[i]
            kuriage = True
        up5 = False
    else:
        if kuriage:
            if N[i] == 4:
                up5, kuriage = True, False
            elif N[i] + 1 < 9 - N[i]:
                ans += N[i] + 1
                kuriage = False
            else:
                ans += 9 - N[i]
        else:
            if N[i] == 5:
                up5 = True
            elif N[i] < 10 - N[i]:
                ans += N[i]
            else:
                ans += 10 - N[i]
                kuriage = True

if up5:
    ans += 5
if kuriage:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
import sys

#read = sys.stdin.buffer.read
#input = sys.stdin.buffer.readline
#inputs = sys.stdin.buffer.readlines

from collections import defaultdict
# mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
# import numpy as np

def main():
	li=[0]+list(map(int,input()))
	n=len(li)
	
	ans=0
	
	for i in range(n):
		a=li[n-1-i]
		if 6<=a:
			ans+=10-a
			li[n-2-i]+=1
		elif a==5:
			if li[n-2-i]<=4:
				ans+=a
			else:
				ans += 10 - a
				li[n - 2 - i] += 1
		else:
			ans+=a
	print(ans)
	
	
if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
N = input()
L = len(N)
ans = 0
t = 0
for i in range(L-1,-1,-1):
    n = int(N[i])+t
    if n == 5:
        if i > 0 and int(N[i-1]) >= 5:
            ans += 10-n
            t = 1
            continue
    if n <= 5:
        ans += n
        t = 0
    else:
        t = 1
        ans += 10-n
if t==1:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
n = input()
k = 0
pay = 0
n_list = []
for i in n[::-1]:
    n_list.append(int(i))
n_list.append(0)
ans = 0
for i in range(len(n_list) - 1):
    num = n_list[i]
    if num < 5:
        ans += num
    elif (num <= 5 and n_list[i + 1] < 5):
        ans += num
    else:
        n_list[i + 1] += 1
        ans += 10 - num

ans += n_list[-1]
print(ans)

Submission status: Accepted

Solution code:
def main():
    N = [0] + [int(i) for i in input()]
    r = 0
    c = 0
    f = 0
    for i in reversed(N):
        if f:
            if i + c >= 5:
                c += 1
                r += 5
            else:
                r += 5
            f = 0
        i += c
        c = 0
        if i < 5:
            r += i
        elif i == 5:
            f += 1
        else:
            c += 1
            r += 10 - i
    print(r)



main()

Submission status: Accepted

Solution code:
n = input()
nl = [0]
for i in range(len(n)):
    nl.append(int(n[i]))
y = 0
for i in range(1, len(nl)+1):
    if nl[-i] <= 4 or (nl[-i] == 5 and nl[-(i+1)] <= 4):
        y += nl[-i]
    else:
        y += (10-nl[-i])
        nl[-(i+1)] += 1
print(y)

Submission status: Accepted

Solution code:
N=input()
n=len(N)
x=0
flag=0
#print(N)
M=[0]*(n+1)
for i in range(n):
  M[i]=int(N[n-1-i])
#print(M)
for i in range(n+1):
  
  m=M[i]
  if m==5:
    x+=5
    flag=1
  elif m<5:
    x+=m
    flag=0
  else:
    x+=(10-m)
    flag=2
  if flag==2:
    M[i+1]+=1
  elif flag==1:
    if M[i+1]>=5:
      M[i+1]+=1
print(x)

Submission status: Accepted

Solution code:
def main():
    N = input()
    reversed_N = ("0" + N)[::-1]

    kuriage = 0
    ans = 0
    for i in range(len(reversed_N)):
        n = int(reversed_N[i]) + kuriage

        if n < 5:
            ans += n
            kuriage = 0
        elif n == 5 and i < len(reversed_N) - 1:
            next_n = int(reversed_N[i + 1])
            if next_n < 5:
                ans += n
                kuriage = 0
            else:
                ans += 10 - n
                kuriage = 1
        else:
            ans += 10 - n
            kuriage = 1

    print(ans)


main()

Submission status: Accepted

Solution code:
S = "000"+input()
S = S[::-1]
N = len(S)

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

ans = 0
up = 0
for i, s in enumerate(S):
    x = int(s) + up
    if x == 10:
        continue
    y = 10 - x
    if x < y:
        ans += x
        up = 0
    elif x > y:
        ans += y
        up = 1
    else:
        ans += x
        if int(S[i + 1]) >= 5:
            up = 1
        else:
            up = 0

print(ans)

Submission status: Accepted

Solution code:
N = list(map(int, input()))
ret = 0
N.reverse()
N.append(0)
N.append(0)
N.append(0)
L = len(N)
for i in range(L-1):
    if N[i] == 5:
        if N[i+1] >= 5:
            ret += 1
            N[i] += 1
    if N[i] > 5:
        ret += 10 - N[i]
        N[i+1] += 1
        if N[i+1] > 9:
            N[i+1] -= 10
            N[i+2] += 1            
    else:
        ret += N[i]
print(ret)

Submission status: Accepted

Solution code:
n = list(map(int, reversed(list(input()))))

a = 0
b = 9999
for x in n:
  temp_a = min(a + x, b + x)
  b = min(a + 10 - x + 1, b + 10 - x - 1)
  a = temp_a

print(min(a, b))

Submission status: Accepted

Solution code:
import collections

def solution():
    n = [int(x) for x in input().strip()]
    res = 0
    carry = 0
    for i in range(len(n)-1, -1, -1):
        cur = n[i] + carry
        if cur == 10:
            carry = 1
        elif 6 <= cur <= 9:
            res += 10-cur
            carry = 1
        elif cur == 5:
            if i > 0 and n[i-1] >= 5:
                carry = 1
                res += 5
            else:
                carry = 0
                res += 5
        else:
            carry = 0
            res += cur
    print(res+carry)

def main():    
    # T = int(input().strip())
    for _ in range(1):
        solution()
    

main()

Submission status: Accepted

Solution code:
N = list(map(int,list(input())))
give = [""]
oturi = [""]
N.reverse()
N.append(0)
for i in range(len(N)):
    if N[i] > 5 or (N[i] == 5 and N[i+1] >= 5):
        N[i+1] += 1
        oturi .append(str(10-N[i]))
        give.append("0")
    else:
        give.append(str(N[i]))
        oturi.append("0")
give.reverse()
oturi.reverse()
give = ("".join(give))
oturi = ("".join(oturi))
#print(give,oturi)
ans = 0
for i in give:
    ans += int(i)
for i in oturi:
    ans += int(i)

print(ans)

Submission status: Accepted

Solution code:
Z = [0,1,2,3,4,5,5,4,3,2,1,1]
C = [0,1,2,5,6,7]
X = [0,1,2,1,2,3]
C=[0,1,2,3,4,5,6,7,8,9]
X=[0,1,2,3,4,5,6,7,8,9]
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] = Z[d0]
    dp[0][1] = Z[d0+1]

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

    return dp[n-1][0]

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

Submission status: Accepted

Solution code:
N = input().strip()


d = int(N[-1])
count_p = d
count_m = 10 - d

for i in range(len(N) - 2, -1, -1):
	d = int(N[i])
	
	new_count_p = min(count_p + d, count_m + (d + 1))
	new_count_m = min(count_p + (10 - d), count_m + (10 - (d + 1)))
	
	count_p = new_count_p
	count_m = new_count_m

count_m += 1

print(min(count_p, count_m))

Submission status: Accepted

Solution code:
n = input()
precise = 0
ok_over = 1
ok_prec = 0
for d in n:
    d = int(d)
    new_over = min(precise + d + 1, ok_over + d + 2, ok_over + 9 - d, ok_prec + d + 1)
    new_prec = min(ok_over + d + 1, ok_prec + d)
    precise += d
    ok_over = new_over
    ok_prec = new_prec
ok_over += 1
print(min(precise, ok_over, ok_prec))

Submission status: Accepted

Solution code:
#map(int,input().split())
n=input()
n='0'+n
l=len(n)
count=0
carry=0
for i in range(l-1,-1,-1):
    x=int(n[i])
    x+=carry
    if x<10-x:
        count+=x
        carry=0
    elif x>10-x:
        count+=10-x
        carry=1
    else:
        count+=5
        if int(n[i-1])<=4:
            carry=0
        else:
            carry=1
print(count)

Submission status: Accepted

Solution code:
N = input()
N = N[::-1]
ans = 0
p = 0
for i in range(len(N)):
    p += int(N[i])
    if p<5:
        ans += p
        p = 0
    elif p==5:
        if i+1==len(N):
            ans += 5
            p = 0
        elif int(N[i+1])>=5:
            ans += 5
            p = 1
        else:
            ans += 5
            p = 0
    else:
        ans += 10-p
        p = 1
if p==1:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
N=input()
N=N[::-1]
n=len(N)
DP=[[0]*2 for i in range(n+1)]
DP[0][1]=float("inf")
for i in range(n):
  nn=int(N[i])
  if nn<9:
    DP[i+1][0]=min(DP[i][0]+nn,DP[i][1]+nn+1)
  else:
    DP[i+1][0]=DP[i][0]+nn
  if nn<9:
    DP[i+1][1]=min(DP[i][0]+(10-nn),DP[i][1]+(10-nn-1))
  else:
    DP[i+1][1]=min(DP[i][0]+(10-nn),DP[i][1])
print(min(DP[n][0],DP[n][1]+1))

Submission status: Accepted

Solution code:
n = list(input())
m = len(n)
for i in range(m):
    n[i] = int(n[i])
ans = 0
kuri = 0
for i in range(m-1,-1,-1):
    n[i] += kuri
    kuri = 0
    #print(n[i])
    if n[i] > 5:
        ans += 10 - n[i]
        kuri = 1
    elif n[i] == 5:
        if i > 0:
            if n[i-1] >= 5:
                kuri = 1
                ans += 5
            else:
                kuri = 0
                ans += 5
        else:
            ans += 5
    else:
        ans += n[i]
if kuri == 1:
    ans += 1
print(ans)

Submission status: Accepted

Solution code:
N=input()
r=0
m=int(N[-1])
for i in range(len(N)-1,0,-1):
    n=m
    m=int(N[i-1])
    if n<5:
        r+=n
    elif n==5:
        if m<5:
            r+=n
        else:
            r+=10-n
            m+=1
    else:
        r+=10-n
        m+=1
r+=m if m<6 else 11-m
print(r)

Submission status: Accepted

Solution code:
def count(x1,x2):
    if x1<=4 or (x1==5 and x2 <=4):
        return x1,0 
    else:
        return 10-x1,1

n='0'+input()
count_sum = 0
digit_plus = 0
for c1,c2 in zip(n[::-1],n[-2::-1]):
    count_add, digit_plus = count(int(c1)+digit_plus,int(c2))
    count_sum += count_add
if digit_plus: count_sum += 1
print(count_sum)

Submission status: Accepted

Solution code:
import sys
range = xrange
input = raw_input

ord0 = ord('0')

S = [ord(c)-ord0 for c in input()]

n = len(S)

i = n - 1
while S[i] == 0:
    i -= 1
S = S[:i + 2]

n = len(S)
DP0 = [0]*(n + 1)
DP1 = [0]*(n + 1)

DP1[0] = 1

for i in range(n):
    if S[i] != 0:
        DP0[i + 1] = min(DP1[i] + 1 + min(9 - S[i], S[i]), DP0[i] + S[i])
        DP1[i + 1] = min(DP0[i] + 1 + min(9 - S[i], S[i]), DP1[i] + 9 - S[i])
    else:
        DP0[i + 1] = min(DP1[i] + 1 + min(10 - S[i], S[i]), DP0[i] + S[i])
        DP1[i + 1] = min(DP0[i] + 1 + min(10 - S[i], S[i]), DP1[i] + 10 - S[i])

print DP0[-1]

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

a = ['0'] + list(input())
n = len(a)-1
for i in range(n):
    a[i] = int(a[i])

res = 0
for i in range(n-1,-1,-1):
    if a[i] <= 4:
        res += a[i]
    elif a[i] == 5:
        if a[i-1] >= 5:
            res += 5
            a[i-1] += 1
        else:
            res += 5

    else:
        res += 10-a[i]
        a[i-1] += 1
print(res)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
sys.setrecursionlimit(300000)


def solve(n: str):
    n = n[::-1]
    ret = 0
    carry = 0
    for i, c in enumerate(n):
        t = int(c)
        t += carry
        if t == 5:
            if i < len(n) - 1 and int(n[i + 1]) >= 5:
                ret += 10 - t
                carry = 1
            else:
                ret += t
                carry = 0
        elif t < 5:
            ret += t
            carry = 0
        else:
            ret += 10 - t
            carry = 1
    if carry:
        ret += 1
    print(ret)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = str(next(tokens))  # type: int
    solve(N)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
a = [int(x) for x in input()]
l = len(a)

a = a[::-1]

ans = 0

for i in range(l):
    if a[i] == 10:
        if i != l-1:
            a[i] = 0
            a[i+1] += 1
        else:
            ans += 1
            break
    if a[i] <= 4:
        ans += a[i]
    elif a[i] == 5:
        if i != l-1 and a[i+1] <= 4:
            ans += 5
        elif i != l-1:
            ans += 5
            a[i+1] += 1
        else:
            ans += 5
    else:
        ans += 10-a[i]
        if i != l-1:
            a[i+1] += 1
        else:
            ans += 1
            break

print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


def main():
    n = [int(i) for i in input()][::-1]

    s = c = 0

    for i in range(len(n)):
        d = n[i] + c
        c = 0

        if (d > 5) or (d == 5 and i + 1 < len(n) and n[i + 1] + 1 > 5):
            s += 10 - d
            c = 1
        else:
            s += d

    print(s + c)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
S = "0" + input()

ans = 0
b = 0
c = 0
for a in S[::-1]:
    A = int(a) + b
    if A == 5 and c == 0:
        ans += 5
        b = 0
        c = 1
    elif A < 5:
        ans += A
        b = 0
        c = 0
    else:
        ans += 10 - A - c
        b = 1
        c = 0

print(ans)

Submission status: Accepted

Solution code:
import sys
# input = sys.stdin.buffer.readline
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getlist():
    return list(map(int, input().split()))
import math
import heapq
from collections import defaultdict, Counter, deque
MOD = 10**9 + 7
INF = 10**15


def main():
    n = input().strip()
    # print(n)
    ans = 0
    n = [int(s) for s in n[::-1] + "0"]
    # print(n)
    for i in range(len(n)):
        if n[i] < 5:
            ans += n[i]
        elif n[i] == 5:
            if n[i+1] >= 5:
                n[i+1] += 1
            ans += 5
        else:
            ans += 10 - n[i]
            n[i+1] += 1

    print(ans)


if __name__ == '__main__':
    main()

"""
9999
3

2916
"""

Submission status: Accepted

Solution code:
n=input()[::-1]
n+="0"
L=len(n)
ans=0
chk=0
flg=0
for i in range(L):
  chk=int(n[i])
  chk+=flg
  if chk==5:
    if int(n[i+1])>=5:
      ans+=5
      flg=1
    else:
      ans+=5
      flg=0
  elif chk>5:
    ans+=10-chk
    flg=1
  else:
    ans+=chk
    flg=0
print(ans+flg)

Submission status: Runtime Error

Solution code:
import functools
import sys

sys.setrecursionlimit(10000000)
n = input()
memo = {}
lenn = len(n)
@functools.lru_cache(None)
def dp(index, carry):
    if index >= lenn:
        return 99999999999999999999 if carry else 0
    v = int(n[index])
    if carry:
        # ぴったり払う
        temp = 10 - v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 9 - v + dp(index+1, 1))
    else:
        # ぴったり払う
        temp = v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 1 + v + dp(index+1, 1))
    return temp

print(min(dp(0, 0), 1 + dp(0, 1)))

Submission status: Runtime Error

Solution code:
import sys
import functools
sys.setrecursionlimit(100000000)
n = input()


@functools.lru_cache(None)
def doit(index: int, carry: int) -> int:
    if index >= len(n):
        return 0 if carry == 0 else 2
    d = int(n[index])
    if carry > 0:
        return min(10 - d + doit(index + 1, 0), 9 - d + doit(index + 1, 1))
    else:
        return min(d + doit(index + 1, 0), d + 1 + doit(index + 1, 1))


print(min(doit(0, 0), 1 + doit(0, 1)))

Submission status: Runtime Error

Solution code:
import functools
import sys

sys.setrecursionlimit(1000000000)
n = input()
memo = {}

@functools.lru_cache(None)
def dp(index, carry):
    if index >= len(n):
        return 99999999999999999999 if carry else 0
    v = int(n[index])
    if carry:
        # ぴったり払う
        temp = 10 - v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 9 - v + dp(index+1, 1))
    else:
        # ぴったり払う
        temp = v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 1 + v + dp(index+1, 1))
    return temp

print(min(dp(0, 0), 1 + dp(0, 1)))

Submission status: Runtime Error

Solution code:
import sys
import functools
sys.setrecursionlimit(10000000)
n = input()


@functools.lru_cache(None)
def doit(index: int, carry: int) -> int:
    if index >= len(n):
        return 0 if carry == 0 else 2
    d = int(n[index])
    if carry > 0:
        return min(10 - d + doit(index + 1, 0), 9 - d + doit(index + 1, 1))
    else:
        return min(d + doit(index + 1, 0), d + 1 + doit(index + 1, 1))


print(min(doit(0, 0), 1 + doit(0, 1)))

Submission status: Runtime Error

Solution code:
import functools
import sys

sys.setrecursionlimit(10000000)
n = input()
memo = {}

@functools.lru_cache(None)
def dp(index, carry):
    if index >= len(n):
        return 99999999999999999999 if carry else 0
    v = int(n[index])
    if carry:
        # ぴったり払う
        temp = 10 - v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 9 - v + dp(index+1, 1))
    else:
        # ぴったり払う
        temp = v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 1 + v + dp(index+1, 1))
    return temp

print(min(dp(0, 0), 1 + dp(0, 1)))

Submission status: Runtime Error

Solution code:
import functools
n = input()
memo = {}

@functools.lru_cache(None)
def dp(index, carry):
    if index >= len(n):
        return 99999999999999999999 if carry else 0
    v = int(n[index])
    if carry:
        # ぴったり払う
        temp = 10 - v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 9 - v + dp(index+1, 1))
    else:
        # ぴったり払う
        temp = v + dp(index+1, 0)
        # お釣りありで払う
        temp = min(temp, 1 + v + dp(index+1, 1))
    return temp

print(min(dp(0, 0), 1 + dp(0, 1)))

Submission status: Runtime Error

Solution code:
s = input()
ans = 0
index = 0
rev = {'0': '9',
       '1': '8',
       '2': '7',
       '3': '6',
       '4': '5',
       '5': '4',
       '6': '3',
       '7': '2',
       '8': '1',
       '9': '0'}
def f(n):
    global ans, index

    lenn = len(n)
    while index < lenn and (n[index] < '5' or (n[index] == '5' and (index == lenn - 1 or n[index+1] <= '4'))):
        ans += int(n[index])
        index += 1
    if index < lenn:
        ans += 1
        f(''.join([rev[t] for t in n if t]))
f(s)
print(ans)

Submission status: Runtime Error

Solution code:
S = input()

cnt = 0
for s in S:
    if int(s) > 5:
        cnt += 10 - int(s)
    else:
        cnt += int(s)

print(cnt + 1 if int(S[1]) > 5 or int(S[0]) > 5 else cnt)

Submission status: Runtime Error

Solution code:
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

from collections import deque
from collections import defaultdict
def main():
    N = S()
    N =  N[::-1]
    cnt = 0
    next = 0
    for i in range(len(N)):
        num = int(N[i])
        num += next
        if num <= 4:
            cnt += num
            next = 0
        elif num >= 6:
            cnt += 10 - num
            next = 1
        else:
            if int(N[i + 1]) <= 4:
                cnt += num
                next = 0
            else:
                cnt += 10 - num
                next = 1

    if next == 1:
        cnt += 1
    print(cnt)
if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

int main() {
  int N;
  cin >> N;
  int Q, R;
  
  int ans = 0;
  while (N > 0) {
    Q = N / 10;
    R = N % 10;
    if (R <= 5) {
      ans += R;
    }
    else {
      ans += 10 - R;
      Q++;
    }  
    N = Q;
  }
  cout << ans << endl;
}

Submission status: Runtime Error

Solution code:
import sys
import numpy as np


def solve(N):
    p, q = 0, 1
    for x in N:
        p, q = min(p + x, q + 10 - x), min(p + x + 1, q + 9 - x)
    print(p)


try:
    sys.winver
    N = np.array([int(_) for _ in input()])
    from numba import jit
    solve = jit(solve, '(i8[:])')
    solve(N)
except:
    if sys.argv[-1] == 'ONLINE_JUDGE':
        import numba
        from numba.pycc import CC
        cc = CC('my_module')
        cc.export('solve', '(i8[:])')(solve)
        # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
        cc.compile()
    else:
        from my_module import solve
        N = np.array([int(_) for _ in input()])
        solve(N)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np


def solve(N):
    p, q = 0, 1
    for x in N:
        p, q = min(p + x, q + 10 - x), min(p + x + 1, q + 9 - x)
    print(p)


try:
    sys.winver
    N = np.array([int(_) for _ in input()])
    from numba import jit
    solve = jit(solve, '(i8[:])')
    solve(N)
except:
    if sys.argv[-1] != 'ONLINE_JUDGE':
        import numba
        from numba.pycc import CC
        cc = CC('my_module')
        cc.export('solve', '(i8[:])')(solve)
        # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
        cc.compile()
    else:
        #from my_module import solve
        #N = np.array([int(_) for _ in input()])
        solve(N)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np


def solve(N):
    p, q = 0, 1
    for x in N:
        p, q = min(p + x, q + 10 - x), min(p + x + 1, q + 9 - x)
    print(p)


try:
    sys.winver
    N = np.array([int(_) for _ in input()])
    from numba import jit
    solve = jit(solve, '(i8[:])')
    solve(N)
except:
    if sys.argv[-1] != 'ONLINE_JUDGE':
        import numba
        from numba.pycc import CC
        cc = CC('my_module')
        cc.export('solve', '(i8[:])')(solve)
        # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
        cc.compile()
    else:
        from my_module import solve
        N = np.array([int(_) for _ in input()])
        solve(N)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np


def solve(N):
    p, q = 0, 1
    for x in N:
        p, q = min(p + x, q + 10 - x), min(p + x + 1, q + 9 - x)
    print(p)


if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', '(i8[:])')(solve)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
else:
    from my_module import solve
    N = np.array([int(_) for _ in input()])
    solve(N)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np


def solve(N):
    p, q = 0, 1
    for x in N:
        p, q = min(p + x, q + 10 - x), min(p + x + 1, q + 9 - x)
    print(p)


if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('solve', '(i8[:])')(solve)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
else:
    from my_module import main
    N = np.array([int(_) for _ in input()])
    solve(N)

Submission status: Runtime Error

Solution code:
n = input()[::-1]
dp = [[0, 0] 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] + int(n[i]), dp[i][1] - int(n[i]) + 10)
    dp[i + 1][1] = min(dp[i][0] + int(n[1]) + 1, dp[i][1] - int(n[i]) + 9)
print(dp[len(n)][0])

Submission status: Runtime Error

Solution code:
n = int(input())
N = [int(i) for i in n]
dp = [[0,0] for _ in range(len(N))]

dp[0][0] = min(N[0],11-N[0])
dp[0][1] = min(N[0]+1,10-N[0])

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

Submission status: Runtime Error

Solution code:
import sys
import numpy as np



def main(N,dp):
    dp[0, 0] = min(N[0], 11 - N[0])
    dp[0, 1] = min(N[0] + 1, 10 - N[0])
    for i in range(1, len(N)):
        dp[i, 0] = min(dp[i - 1, 0] + N[i], dp[i - 1, 1] + 10 - N[i])
        dp[i, 1] = min(dp[i - 1, 0] + N[i] + 1, dp[i - 1, 1] + 9 - N[i])
    print(dp[-1][0])


if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8[:],i8[:,:])')(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
else:
    from my_module import main
    N = np.array([int(_) for _ in input()])
    dp=np.zeros((2,len(N)),dtype=np.int64)
    main(N,dp)

Submission status: Runtime Error

Solution code:
import sys
import numpy as np



def main(N):
    dp=np.zeros((2,len(N)),dtype=np.int64)
    dp[0, 0] = min(N[0], 11 - N[0])
    dp[0, 1] = min(N[0] + 1, 10 - N[0])
    for i in range(1, len(N)):
        dp[i, 0] = min(dp[i - 1, 0] + N[i], dp[i - 1, 1] + 10 - N[i])
        dp[i, 1] = min(dp[i - 1, 0] + N[i] + 1, dp[i - 1, 1] + 9 - N[i])
    print(dp[-1][0])


if sys.argv[-1] == 'ONLINE_JUDGE':
    import numba
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i8[:],)')(main)
    # b1: bool, i4: int32, i8: int64, double: f8, [:], [:, :]
    cc.compile()
else:
    #from my_module import main
    N = np.array([int(_) for _ in input()])
    main(N)