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:
# -*- coding: utf-8 -*-

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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
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 += 10**i * a
        A.append(a)
    # A += 10**(len(M)) * carry
    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))):
        # print(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

    # print(N)
    # print(A)
    # B = int(A) - int(N)
    # for c in str(B):
    #     ans += int(c)
    # for c in str(A):
    #     ans += int(c)

    # print('   ', B)
    return ans


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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
  s=input()
  #while s%10==0:
  #    s//=10
  #s=9**100
  #s=str(s)
  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()

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    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): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    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)

Submission status: Accepted

Solution code:
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: # intI == 5
    if len(n) != i+1 and int(n[i+1]) >= 5:
      kuriage = 1
      sum += (10 - intI)
    else:
      kuriage = 0
      sum += intI  
print(sum + kuriage)

Submission status: Accepted

Solution code:
n = list(map(int, list("0" + input())))
ans = 0
for i in range(len(n)):
    check = int(n[-i-1])
    if 0 <= check <= 4:
        ans += check
    elif 6 <= check <= 9:
        ans += 10 - check
        temp = 2
        while n[-i-temp] == 9:
            n[-i-temp] = (int(n[-i-temp]) + 1) % 10
            temp += 1
        else:
            n[-i-temp] = (int(n[-i-temp]) + 1) % 10
    else:
        ans += 5
        check2 = n[-i-2]
        if check2 >= 5:
            temp2 = 2
            while n[-i-temp2] == 9:
                n[-i-temp2] = (int(n[-i-temp2]) + 1) % 10
                temp2 += 1
            else:
                n[-i-temp2] = (int(n[-i-temp2]) + 1) % 10
print(ans)

Submission status: Accepted

Solution code:
N = list('0'+input())
l = len(N)
ans = 0
i = l-1
while i > 0:
    if int(N[i])>=6 or (int(N[i]) == 5 and int(N[i-1])>=5):
        ans+=10-int(N[i])
        i-=1
        while N[i] == '9':
            i-=1
        N[i] = str(int(N[i])+1)
    else:
        ans+=int(N[i])
        i-=1
ans+=int(N[0])
print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)


n = input()

# a[i]: ans for n[:i]
# a = [0 for i in range(len(n) + 1)]
# a[0] = 0
# a[1] = max(a[0] + int(n[0]), (10 - int(n[0])) + 1)
# a[2] = max(a[1] + int(n[1]), a[0] + (10 - int(n[1])) + 1)

# def inv(n):
#     n_new = list()
#     for i in range(len(n)):
#         if n[i] == '9':
#             n_new.append(0)
#         else:
#             n_new.append(9 - int(n[i]))
#     for i in range(len(n)):
#         if n_new[-i] != 9:
#             n_new[-1] += 1
#             break
#         else:
#             n_new[-1] = 0

#     return ''.join(map(str, n_new))


# def func(n, calc_inv=True):
#     if len(n) == 0:
#         return 0

#     if calc_inv:
#         return min(1 + func(inv(n), calc_inv=False), func(n, calc_inv=False))
    
#     else:            
#         return int(n[0]) + func(n[1:])

# print(func(n))

# a = [0 for i in range(len(n) + 1)]
# for i in range(len(n)):
#     if int(n[i]) < 5:
#         a[i + 1] += int(n[i])
#     elif int(n[i]) > 5:
#         a[i] += 1
#         a[i + 1] -= (10 - int(n[i]))
#     else: # 5
#         if a[i] >= 0:
#             a[i + 1] += 5
#         else:
#             a[i] += 1
#             a[i + 1] - 5

# print(a)
# print(sum(map(abs, a)))


a = [0 for i in range(len(n) + 1)]
for i in range(1, len(n) + 1):
    # print(a)
    m = int(n[-i]) + a[i - 1]
    # print(m)
    if m < 5:
        a[i - 1] = m
    elif m > 5:
        a[i] += 1
        a[i - 1] = - (10 - m)
    else: # 5
        if i != len(n) and int(n[-i-1]) >= 5:
            a[i] += 1
            a[i - 1] = - m
        else:
            a[i - 1] = m

# print(a[::-1])
print(sum(map(abs, a)))

Submission status: Accepted

Solution code:
n = input()
value = 0
answer = 0
over = 0
five = 0

for i in range(len(n)+1):
    if i == len(n):
        if over == 1:
            answer += 1
            break
        else:
            break
    value = int(n[len(n)-1-i]) + over
    if five == 1:
        if value >= 5:
            answer += (10 - value - 1)
            five = 0
            over = 1
        else:
            answer += value
            five = 0
            over = 0
    else:
        if value > 5:
            answer += (10 - value)
            over = 1
        elif value == 5:
            answer += 5
            five = 1
            over = 0
        else:
            answer += value
            over = 0

print(answer)

Submission status: Accepted

Solution code:
def main():
    a = list(map(int, list(input())))
    a.reverse()
    n = len(a)
    a += [0]
    b = [i for i in a]
    cnt = 0
    for i in range(len(a)):
        if b[i] > 5 or (b[i] == 5 and b[i+1] >= 5):
            b[i] = 0
            b[i+1] += 1
    cnt = sum(b)
    for i in range(n):
        if a[i] <= b[i]:
            cnt += b[i]-a[i]
        else:
            b[i] += 10
            b[i+1] -= 1
            cnt += b[i]-a[i]
    print(cnt)


main()

Submission status: Accepted

Solution code:
"""
N,K = list(map(int,input().split()))
A = list(map(int,input().split()))

A.sort()


def bisect(i,V):
    l = i+1
    r = N-1
    if A[i]*A[r]<V:
        return r-i
    if [i]*A[l]>=V:
        return 0
    while r-l>1:
        if A[i]*A[(l+r)//2]<V:
            l = (l+r)//2
        else:
            r = (l+r)//2
    return r

"""


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

count = 0
flag = False
for i in range(len(N)):
    s = int(N[i])
    if not flag:

        if s>5:
            count += 10-s
            flag = True
        elif s==5:
            count += 5
            if i<len(N)-1:
                t = int(N[i+1])
                if t>=5:
                    flag=True
        else:
            count += s
            flag=False
    else:

        if s+1>=10:
            #A.append("0")
            #B.append("0")
            flag = True
        elif s+1>5:
            count += 10-s-1
            #A.append("0")
            #B.append(str(10-s-1))
            flag = True
        elif s+1==5:
            count += 5
            if i<len(N)-1:
                t = int(N[i+1])
                if t>=5:
                    flag=True
                else:
                    flag=False
            else:
                flag=False

        else:
            count += s+1

            flag=False

if flag:
    count+=1

print(count)

Submission status: Accepted

Solution code:
n = list(map(int, list(input())))
n.reverse()
n.append(0)
l = len(n)
cnt = 0
for i in range(l):
    if n[i] <= 4:
        cnt += n[i]
    elif n[i] == 5:
        if n[i+1] >=5:
            cnt += 10-n[i]
            n[i+1] += 1
        else:
            cnt += n[i]
    else:
        cnt += 10-n[i]
        n[i+1] += 1
print(cnt)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


def main():
    S = input().strip()

    ans = 0
    S_rev = S[::-1]
    kuriage = 0
    for i, s in enumerate(S_rev):
        if i == len(S) - 1:
            if int(s) == 9 and kuriage == 1:
                ans += 1
            elif int(s) + kuriage >= 6:
                ans += 10 - int(s) - kuriage + 1
            else:
                ans += int(s) + kuriage
        else:
            if int(s) == 9 and kuriage == 1:
                continue
            if int(s) + kuriage >= 6:
                ans += 10 - int(s) - kuriage
                kuriage = 1
            elif int(s) + kuriage == 5 and int(S_rev[i + 1]) >= 5:
                ans += 10 - int(s) - kuriage
                kuriage = 1
            else:
                ans += int(s) + kuriage
                kuriage = 0
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N=input()
a=0
k=0
for i in range(len(N)-1,-1,-1):
    n=int(N[i])+k
    if n<6:
        a+=n
        if n==5 and i!=0 and int(N[i-1])>4:
            k=1
        else:
            k=0
    elif n!=10:
        a+=10-n
        k=1
    else:
        a+=0
        k=1
a+=k
print(a)

Submission status: Accepted

Solution code:
ans=0
s=[int(i) for i in input()[::-1]]+[0]
i=0
while i<len(s):
    t=s[i]
    if t<=4:
        ans+=t
        i+=1
    elif t==5:
        if s[i+1]>=5:
            ans+=6
            i+=1
            t=s[i]
            while t>=4:
                if t==4:
                    if s[i+1]<5:
                        ans+=4
                        i+=1
                        break
                ans+=9-t
                i+=1
                t=s[i]
        else:
            ans+=5
            i+=1
    elif t>5:
        ans+=11-t
        i+=1
        t=s[i]
        while t>=4:
            if t==4:
                if s[i+1]<5:
                        ans+=4
                        i+=1
                        break
            ans+=9-t
            i+=1
            t=s[i]
print(ans)

Submission status: Accepted

Solution code:
S = input()[::-1]
lenS = len(S)
S = list(map(int, list(S)))

cnt = 0
mod = 0

for i in range(lenS - 1):
    v = int(S[i]) + mod
    if v < 5:
        cnt += v
        mod = 0
    elif v == 5:
        cnt += 5
        if S[i + 1] >= 5:
            mod = 1
        else:
            mod = 0
    elif v > 5:
        cnt += 10 - v
        mod = 1

ss = S[-1] + mod
if ss <= 5:
    cnt += ss
    mod = 0
else:
    cnt += 10 - ss
    mod = 1

print(cnt if mod == 0 else cnt + 1)

Submission status: Accepted

Solution code:
M = [int(i) for i in input()][::-1] + [0]
ans = 0
flag = 0
for i in range(len(M)):
    if M[i] > 5:
        if M[i-1] == 5:
            ans += 10-M[i]+4
            M[i-1] = 0
            M[i] = 0
            M[i+1] += 1
        else:
            ans += 10-M[i]
            M[i+1] += 1
            M[i] = 0
    elif M[i] == 5 and M[i-1] == 5:
        M[i-1] = 0
        M[i] = 0
        M[i+1] += 1
        ans += 9
print(sum(M)+ans)

Submission status: Accepted

Solution code:
def main():
    N = input()
    r = 0
    x = 0
    n = len(N)
    p = 0
    o = 0
    for i in N:
        j = int(i)
        np = min(p + j, o + j)
        if o != 0:
            no = min(o + 9 - j, p + 11 - j)
        else:
            no = p + 11 - j
        p = np
        o = no
    print(min(p,o))
main()

Submission status: Accepted

Solution code:
l = list(input())
l2 = []
for i in l[::-1]:
    l2.append(int(i))

l2.append(0)
count = 0

for i in range(len(l2)):
    if l2[i] <= 4:
        count += l2[i]
    elif l2[i] == 5:
        if l2[i+1] <=4:
            count += 5
        else:
            count += 5
            l2[i+1] += 1
    else:
        count += 10-l2[i]
        l2[i+1] += 1
print(count)

Submission status: Accepted

Solution code:
n = "0"+input()
a = [0, 0]
flag = True

for i in reversed(n):
    b = int(i)
    c=[0,0]
    if flag:
        flag = False
        c[0] = b
        c[1] = 10 - b
    else:
        c[0] = min(a[0] + b, a[1] + b + 1)
        c[1] = min(a[0] + 10 - b, a[1] + 10 - b - 1)
    a=c[:]
print(min(a))

Submission status: Accepted

Solution code:
nl = list(input())
n = len(nl)

ans = 0
dp = [[0, 0] for i in range(n+1)]
for idx, i in enumerate(nl[::-1]):
    i = int(i)
    if idx == 0:
        dp[1][0] = dp[idx][0] + i
        dp[1][1] = dp[idx][0] + 10 - i
    else:
        dp[idx+1][0] = min(dp[idx][0] + i, dp[idx][1] + i + 1)
        dp[idx+1][1] = min(dp[idx][0] + 10 - i, dp[idx][1] + 10 - i - 1)
print(min(dp[-1][0], dp[-1][1]+1))

Submission status: Accepted

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

daikin = 0
otsuri = 0

cnt = 0
for i in range(len(n)-1, 0, -1):
  if n[i] == 10:
    n[i-1] += 1
    continue

  if n[i] < 5:
    cnt += n[i]
    daikin += n[i]
  elif n[i] == 5:
    if n[i-1] < 5:
      cnt += 5
    else:
      cnt += 5
      n[i-1] += 1
  else:
    cnt += 10 - n[i]
    otsuri
    if i != 0:
      n[i-1] += 1

if n[0] <= 5:
  cnt += n[0]
else:
  cnt += 11 - n[0]

print(cnt)

Submission status: Accepted

Solution code:
A = input()
S = list(map(int,list(A)))
N = len(S)
output = 0
for i in range(N):
    t = N-1-i
    M = S[t]
    if M>5:
        output += 10-M
        S[t-1]+=1
    elif M==5:
        if S[t-1]>=5:
            output += 10-M
            S[t-1]+=1
        else:
            output+=M
    else:
        output += M
if S[0]>5:
    output+=1
if A=="5":
    output = 5
print(output)

Submission status: Accepted

Solution code:
N = ['0'] + list(input()) + ['0']
# print (N)
n = len(N)
ans = 0
flag = False
count = 0
for i in range(n - 1, 0, -1):
    s = int(N[i])
    
    if flag:
        s += 1
        N[i] = str(s)
    else:
        pass

    if s <= 5:
        next_ = int(N[i - 1])
        if s == 5 and  next_ >= 5:
            # ans -= 1
            ans += s
            flag = True

        else:
            ans += s
            flag = False
    else:
        ans += 10 - s
        flag = True


if flag:
    ans += 1

count = 0
for s in N:
    if s == '5':
        count += 1
    else:
        ans -= max(count -2, 0)
        count = 0


print (ans)

Submission status: Accepted

Solution code:
a = list(map(int,list(input())))[::-1]
a.append(0)
ans = 0
for i in range(len(a)):
  if a[i] >= 6 or (a[i] == 5 and a[i+1] >= 5):
    a[i] = 10-a[i]
    a[i+1] += 1
print(sum(a))

Submission status: Accepted

Solution code:
def nasu(N):
  ans = 0
  i = 0
  while i < len(N):
    t = N[i]
    if t < 5 or (t == 5 and i == len(N) - 1) or (t == 5 and N[i + 1] <= 4):
      ans += t
      i += 1
    else:
      ans += 1
      ans += 9 - t
      i += 1
      while i < len(N):
        t = N[i]
        if t < 4 or (t == 4 and i == len(N) - 1) or (t == 4 and N[i + 1] <= 4):
          ans += 1
          break
        else:
          ans += 9 - t
          i += 1
      else:
        ans += 1

  return ans


N = list(map(int, list(input())))

print(nasu(N))

exit()
for i in range(500, 600):
  N = list(map(int, list(str(i))))
  print(i, nasu(N))

Submission status: Accepted

Solution code:
num = list(input())
num = list(map(int, num))
length = len(num)

ans = 0

# isspecial = True
# # 9が１子以上続いたあとに5
# if num[-1] == 5:
#     for i in reversed(range(length - 1)):
#         if num[i] != 9:
#             isspecial = False
#             break
# else:
#     isspecial = False
# if isspecial:
#     print(6)
#     exit()    

for i in reversed(range(1, length)):
    digit = num[i]
    if digit < 5:
        ans += digit
    elif i > 0 and digit == 5 and num[i-1] < 5:
        ans += digit
    else:
        ans += (10 - digit)
        if i > 0:
            num[i-1] += 1
        else:
            ans += 1

digit = num[0]
if digit <= 5:
    ans += digit
else:
    ans += (11 - digit)

print(ans)

Submission status: Accepted

Solution code:
def f(i):
    while True:
        a[i]=(a[i]+1)%10
        if a[i]==0: i+=1
        else: break

s=input()
a=[]
for i in range(len(s)-1,-1,-1):
    a.append(int(s[i]))
a.append(0)

ans=0
for i in range(len(a)-1):
    if a[i]<5: ans+=a[i]
    elif a[i]==5:
        if a[i+1]<5: ans+=5
        else:
            ans+=5
            f(i+1)

    else:
        ans+=10-a[i]
        f(i+1)

if a[-1]!=0: ans+=1

print(ans)

Submission status: Accepted

Solution code:
import bisect

S=input()
dig=len(S)

ans=0

b=0#繰り上がり
for i in range(dig):
    a=int(S[dig-i-1])+b
    if a<=4:
        ans+=a
        b=0
    elif a>=6:
        ans+=(10-a)
        b=1
    else:#a==5
        if i==dig-1:
            ans+=5
            b=0
        else:
            if int(S[dig-i-2])>=5:
                b=1
            else:
                b=0
            ans+=5


        

if b==1:
    ans+=1

    
print(ans)

Submission status: Accepted

Solution code:
def main():
    N = input()
    ans = 0
    carry = 0
    prev_5 = False
    for c in N[::-1]:
        if prev_5 and int(c) >= 5:
            carry = 1
        if int(c) + carry <= 4:
            ans += int(c) + carry
            carry = 0
            prev_5 = False
        elif int(c) + carry == 5:
            ans += 10 - (int(c) + carry)
            carry = 0
            prev_5 = True
        else:
            ans += 10 - (int(c) + carry)
            carry = 1
            prev_5 = False
    if carry == 1:
        ans += 1
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
a=input()
N=len(a)
count=0
bonus=0
for i in range(N-1,-1,-1):
    if int(a[i])+bonus>=6 or (int(a[i])+bonus==5 and (i!=0 and int(a[i-1])>=5)):
        count+=(10-int(a[i])-bonus)
        if i!=0:
            bonus=1
        else:
            count+=1
    else:
        count+=int(a[i])+bonus
        bonus=0
print(count)

Submission status: Accepted

Solution code:
import sys
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

s = S()
t = s[::-1]
N = len(s)

dp = [[MAX_INT]*2 for i in range(N+1)]
dp[0][0] = 0
for i in range(N):
  num = int(t[i])
  dp[i+1][0] = min(dp[i][0] + num, dp[i][1] + num +1)
  dp[i+1][1] = min(dp[i][0] + 10-num, dp[i][1] + 10-num-1)
print(min(dp[-1][0], dp[-1][1]+1))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def solve():
    N = input()[::-1]+'00'
    res = 0
    c = 0
    for i in range(len(N)-1):
        r = int(N[i])+c
        c = r//10
        r %= 10
        r_ = (int(N[i+1])+c)%10
        if r < 5 or (r==5 and r_ < 5):
            res += r
        else:
            res += 10-r
            c += 1
    return str(res)

if __name__ == '__main__':
    print(solve())

Submission status: Accepted

Solution code:
N = list(map(int,input()))
L = len(N)
ans0 = 0
ans1 = 100
for i in range(L):
    k = N[-i-1]
    ans0, ans1 = (min(ans0+k, ans1 + k+1),
                  min(ans0 + 10-k, ans1 + 9-k))
ans = min(ans0, ans1+1)
print(ans)

Submission status: Accepted

Solution code:

N = input()

ans = 0

dp = [0,2]

for i in range(len(N)):

    ndp = [float("inf"),float("inf")]

    num = int(N[-1-i])

    ndp[0] = min( dp[0] + num , dp[1] + num )
    ndp[1] = min( dp[0] + 2 + 9 - num , dp[1] + 9 - num)

    dp = ndp

    #print (dp)

print (min(dp))

Submission status: Accepted

Solution code:
n = input()
l = len(n)
now = 0
m = 1
p = 0
for i in range(l):
  d = int(n[i])
  M = [m,p]
  P = [m,p]
  M[0] += 9-d
  P[0] += 10-d
  M[1] += 1+d
  P[1] += d
  m = min(M)
  p = min(P)
  #print(M,P)
m += 1
print(min(m,p))

Submission status: Accepted

Solution code:
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 999999999
R = 10**9 + 7

def ddprint(x):
  if DBG:
    print(x)

n = ins()
nrev = n[::-1]
m = len(n)
l = [0]*(m+1)
r = [0]*(m+1)
r[m] = 1
for k in range(m,0,-1):
    p = int(nrev[k-1])
    l[k-1] = min(l[k]+p, r[k]+10-p)
    if k>0:
        r[k-1] = min(l[k]+p+1, r[k]+10-p-1)
print(l[0])

Submission status: Accepted

Solution code:
n = input()

a = n[::-1] + "0"

prev_a = int(a[0])
prev_b = 10 - int(a[0])

# dp[下の桁から][繰り上げるかどうか]
for i in range(1, len(a)):
    x = int(a[i])
    y = x + 1
    aa = min([x + prev_a, y + prev_b])
    bb = min([(10 - x) + prev_a, (10 - y) + prev_b])
    prev_a = aa
    prev_b = bb

print(min(aa, bb))

Submission status: Accepted

Solution code:
n = str(input())
l = len(n)
c = 0
n = "00"+ n
dnow = int(n[l+1])
for i in range(l+1):
  dnext = int(n[l-i])
  if  dnow <= 4:
    c += dnow
  elif dnow == 5:
    if dnext <= 4:
      c += 5
    else:
      dnext += 1
      c += 5
  elif dnow == 10:
    dnext += 1
  else:
    c += 10 - dnow
    dnext += 1
  dnow = dnext
print(c)

Submission status: Accepted

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

stdin = open(0)
N = [int(x) for x in stdin.read().rstrip()]


def solve(N):
    L = len(N)
    # n円の場合、n+1円の場合
    dp = 0, 1
    for n in N:
        a = min(dp[0] + n, dp[1] + 10 - n)
        b = min(dp[0] + n + 1, dp[1] + 10 - (n + 1))
        dp = a, b
    return dp[0]


print(solve(N))

Submission status: Accepted

Solution code:
n = input()[::-1]
cnt = 0
flag = 0
for i in range(len(n)-1):
    if int(n[i])+flag < 5:
        cnt += int(n[i])+flag
        flag = 0
    elif int(n[i])+flag > 5:
        cnt += (10-int(n[i])-flag)
        flag = 1
    else:
        if int(n[i+1]) >= 5:
            cnt += (10 - int(n[i])-flag)
            flag = 1
        else:
            cnt += (int(n[i]) + flag)
            flag = 0
if int(n[-1])+flag > 5:
    cnt += (11 - int(n[-1])-flag)
else:
    cnt += int(n[-1])+flag
print(cnt)

Submission status: Accepted

Solution code:
n=input()
keta=[0,0]
for i in range(len(n)):
	keta.append(int(n[i]))
ans=0
for i in range(len(keta)-1):
	if keta[-i-2]>=5:
		if keta[-i-1]>=5:
			ans+=10-keta[-i-1]
			keta[-i-2]+=1
		else:
			ans+=keta[-i-1]
	else:
		if keta[-i-1]>=6:
			ans+=10-keta[-i-1]
			keta[-i-2]+=1
		else:
			ans+=keta[-i-1]
print(ans)

Submission status: Accepted

Solution code:
s = input().strip()
s = s[::-1]
r = 0
b = 0
N = len(s)
dp1 = [0] * (N+1)
dp2 = [0] * (N+1)
dp1[1] = int(s[0])
dp2[1] = 11 - int(s[0])
for i, c in enumerate(s[1:]):
    i += 1
    c = int(c)
    dp1[i+1] = min(dp1[i] + c, dp2[i] + c)
    dp2[i+1] = min(dp1[i] + 11 - c, dp2[i] + 9 - c)
#print(dp1)
#print(dp2)

print(min(dp1[-1], dp2[-1]))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
s=input()
state=0
mai=0
for i in range(len(s)):
  k=int(s[len(s)-1-i])
  if state==1:
    k=k+1
    if k<0:
      k=10+k
  elif state==2:
    if k>=5:
      k=k+1
      if k<0:
        k=10+k
  if k>5:
    mai+=10-k
    state=1
  elif k<5:
    mai+=k
    state=0
  elif k==5:
    state=2
    mai+=k
if k>=6:
  mai+=1
print(mai)

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
read = sys.stdin.read


n = "".join(["0",input()])

ov = 10**9
eq = 0

L = len(n)-1
for i,x in enumerate(n):
    x = int(x)
    ov,eq = min(ov+9-x,eq+x+1), min(ov+10-x, eq+x)


print(eq)

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    s=SI()
    n=len(s)
    ans=0
    nxt=0
    for i in range(n-1,-1,-1):
        now=int(s[i])+nxt
        if now>5 or (i>0 and now==5 and int(s[i-1])>4):
            nxt=1
            ans+=10-now
        else:
            ans += now
            nxt = 0
    ans+=nxt
    print(ans)

main()

Submission status: Accepted

Solution code:
n_s = input()
n_s = n_s[::-1]
#n = int(n_s)

pay = 0
back = 0
flag = 0

dp = [[0,0] for _ in range(len(n_s) + 1)]

dp[0][0] = int(n_s[0])
dp[0][1] = 10 - int(n_s[0])

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

print(min(dp[-1]))

Submission status: Accepted

Solution code:
N=list(map(int,list("0"+input())))

ans = 0
while N:
    n = N.pop()
    if n>=10:
        N[-1] += 1
        n -= 10
    if n>=6:
        ans += 10-n
        N[-1] += 1
    elif n==5:
        if N[-1] >= 5:
            N[-1] += 1
            ans += 10-n
        else:
            ans += n
    else:
        ans += n
print(ans)