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:
n = str(input().rstrip())

ans = 0

a = list(map(int, list(n)))
a = a[::-1]
a.append(0)
for i in range(len(a) - 1):
    c = a[i]
    if c < 5:
        ans += c
    else:
        if c == 5 and a[i+1] < 5:
            ans += 5
        else:
            a[i+1] += 1
            ans += 10 - c
ans += a[-1]

print(ans)

Submission status: Accepted

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


ans = 0
flag = False
flag5 = False
for i in range(len(N)-1, -1, -1):
    x = N[i]
    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
print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n = list(input())
n = [int(i) for i in n]
n.reverse()
l = len(n)
ans = 0
for i in range(l-1):
    if (n[i]==5 and n[i+1]>=5) or n[i]>5:
        n[i+1] += 1
        ans += 10-n[i]
    else:
        ans += n[i]
ans += 11-n[-1] if n[-1]>5 else n[-1]
print(ans)

Submission status: Accepted

Solution code:
n = list(map(int, list(input())))
n = n[::-1] + [0]
d = len(n)

ans = 0
for i, k in enumerate(n):
    if k < 5:
        ans += k
    elif k == 5 and n[i + 1] < 5:
        ans += k
    else:
        ans += 10 - k
        n[i + 1] += 1
print(ans)

Submission status: Accepted

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

def solve(N: str):
    n = list(map(int,list(N)))
    kuriage = 0
    LEN = len(n)
    pay_count = 0

    for i in range(LEN-1,-1,-1):
        if i != 0:
            if n[i-1] >= 5:
                if n[i]+kuriage <= 4:
                    pay_count += n[i]+kuriage
                    kuriage = 0
                else:
                    pay_count += 10-(n[i]+kuriage)
                    kuriage = 1
            else:
                if n[i]+kuriage <= 5:
                    pay_count += n[i]+kuriage
                    kuriage = 0
                else:
                    pay_count += 10-(n[i]+kuriage)
                    kuriage = 1
        else:
            if n[i]+kuriage <= 5:
                pay_count += n[i]+kuriage
                kuriage = 0
            else:
                pay_count += 10-(n[i]+kuriage)
                kuriage = 1

    if kuriage == 1:
        pay_count += 1
    print(pay_count)
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

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

dp1 = [0]
dp2 = [1]

for x in N:
    x = int(x)

    r = dp1[-1]+x
    if x<9: r = min(r, dp2[-1]+x+1)
    dp1.append(r)
    dp2.append(min(dp1[-2]+10-x, dp2[-1]+9-x))

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

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
S = [0] + list(map(int, list(input())[: -1]))

dp = [[float("inf")] * 2 for _ in range(len(S) + 1)]
dp[-1][0] = 0
for i in range(len(dp) - 1, 0, -1):
  for j in range(2):
    if S[i - 1] + j <= 5:
      dp[i - 1][0] = min(S[i - 1] + j + dp[i][j], dp[i - 1][0])
    if S[i - 1] + j >= 5:
      dp[i - 1][1] = min(10 - (S[i - 1] + j) + dp[i][j], dp[i - 1][1])

print(min(dp[0]))

Submission status: Accepted

Solution code:
N=list(map(int,input()))
N.reverse()
N.append(0)
n=len(N)
pay=[0]*n
price = list(N)

for i in range (n):
    if N[i]>5:
        pay[i]=0
        N[i+1]=N[i+1]+1
    elif  N[i]<5:
        pay[i]=N[i]
    else:
        if N[i+1]>=5:
            pay[i]=0
            N[i+1]=N[i+1]+1
        else:
            pay[i]=N[i]


#print(price)
#print(pay)
sum_pay=sum(pay)

c=0
for i in range (n):
    if pay[i]-price[i]>=0:
        c=c+pay[i]-price[i]
    else:
        c=c+10+pay[i]-price[i]
        pay[i+1]=pay[i+1]-1

sum_otsuri=c

#print(sum_otsuri)
#print(sum_pay)

sum=sum_otsuri+sum_pay
print(sum)

Submission status: Accepted

Solution code:
n = str(input())[::-1]
n = n + "0"
l = len(n)
ans = 0
flg = 0
check = 0

for i in range(l):
    check = int(n[i])
    check += flg
    if check == 5:
        if int(n[i + 1]) >= 5:
            ans += 5
            flg = 1
        else:
            ans += 5
            flg = 0
    elif check > 5:
        ans += 10 - check
        flg = 1
    else:
        ans += check
        flg = 0
print(ans + flg)

Submission status: Accepted

Solution code:
n = input()
N = []
ans = 0
l = len(str(n))

for i in range(l):
    N.append(int(n[-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)

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())))
N.reverse()
N=N+[0]
cnt = 0
for i in range(len(N)):
  n=N[i]
  if n<5:
    cnt+=n
  elif n==5:
    cnt+=n
    if N[i+1]>=5:
      N[i+1]+=1
  else:
    cnt+=10-n
    N[i+1]+=1
print(cnt)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
print(dp[0])

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
dp0=[float('inf')]*(keta+1)
dp1=[float('inf')]*(keta+1)
dp0[0]=0
# dp[0]=[0,1]
# print(dp)
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(dp)
print(min(dp0[-1],dp1[-1]+1))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:

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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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=[int(n[i]) for i in range(len(n))]
# for i in range(len(n)):
#     lst.append(int(n[i]))
# n=int(n)

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

# dp=[[float('inf')]*2 for i in range(keta+1)]
dp=[[0,1]]
for i in range(keta):
    dp.append([float('inf')]*2)
# dp[0]=[0,1]
# print(dp)
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(dp)
print(min(dp[-1][0],dp[-1][1]+1))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
        # print(res, ans)
        assert str(res) == str(ans)


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

Submission status: Accepted

Solution code:
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):
    # print(N, kyaku, mise)
    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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
N = input()

keta = len(N)

#ans = [0] * ( keta + 1 )
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:
        #ans[i] = 0
        N_list[i+1] += 1
        ans_num += 10 - N_list[i]
    elif N_list[i] > 5:
        #ans[i] = 0
        N_list[i+1] += 1
        ans_num += 10 - N_list[i]
    else:
        #ans[i] =  N_list[i]
        ans_num += N_list[i]
#print(ans)
print(ans_num)

Submission status: Accepted

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

Submission status: Accepted

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

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 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()

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:

#    0, 1, 2, 3, 4, 5, 6, 7, 8, 9
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]
            #s.append(P[c])
        elif c == 5:
            if i == len(N)-1:
                p += 5
                #s.append(5)
                b = 0
            else:
                if N[i+1] < 5:
                    p += 5
                    b = 0
                    #s.append(5)
                else:
                    p += 5    
                    b = 1
                    #s.append(0)
        elif c > 5:
            b = 1
            p += X[c]
            #s.append(P[c])
        else:
            b = 0
            p += X[c]
            #s.append(P[c])
    if b:
        s.append(b)
        pass
    #print(b, file=sys.stderr)
    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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
        #print(n, ans)
    if up: ans += 1
    print(ans)

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
#from math import sqrt
#from heapq import heappush, heappop
#from collections import deque

#a, b = [int(v) for v in input().split()]

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)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
# 整数の入力
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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
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)
    #print(n_list)

print(counter)

Submission status: Accepted

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

Submission status: Accepted

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

            # carry over
            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

#            print(D[l], ans)

        return ans


if __name__ == '__main__':

    # standard input
    N = input()

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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
# MOD = 998244353


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)

# maekaramiteku
# dp[i][j]: i まで見て最小の答え、反転してるかどうか
dp = [[IINF, IINF] for _ in range(N + 1)]
dp[0][0] = 0
dp[0][0] = 0
for i in range(N):
    # 1 使って反転できる
    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]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log #log2ないｙｐ
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: #5
            ans += t
            try:
                if S[i+1]>=5:
                    S[i+1] += 1
            except:
                pass
    print(ans+int(flag))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
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]))
# n=int(n)

keta=len(lst)
ans=0
lst.reverse()
# print(lst)
# dp=[[float('inf')]*2 for i in range(keta+1)]
dp=[]
for i in range(keta+1):
    dp.append([float('inf')]*2)
dp[0]=[0,1]
# print(dp)
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(dp)
print(min(dp[-1][0],dp[-1][1]+1))