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

Solution (Python):

n=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)

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

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

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

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

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

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

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

Solution (Python):


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

if __name__ == '__main__':
    main()

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

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




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



if __name__ == "__main__":
    main()

Solution (Python):
inf=float('inf')
s=input()[::-1]
n=len(s)
dp=[2*[inf]for _ in range(n)]
dp[0]=[int(s[0]),10-int(s[0])]
for i in range(1,n):
  if s[i]=="9":
    dp[i][1]=min(dp[i-1][1],dp[i-1][0]+1)
    dp[i][0]=dp[i-1][0]+9
  else:
    dp[i][0]=int(s[i])+min(dp[i-1][0],dp[i-1][1]+1)
    dp[i][1]=min(9-int(s[i])+dp[i-1][1],10-int(s[i])+dp[i-1][0])
print(min(dp[n-1][0],dp[n-1][1]+1))

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

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

Solution (Python):
import sys

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()
    
    ans = 0
    n = [int(s) for s in n[::-1] + "0"]
    
    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
"""

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