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: Runtime Error

Solution code:
def main():
    from builtin import min
    N = int(input())

    a = 0 // carried
    b = 0 // not carried
    while N != 0:
        t = N % 10
        a = min(a + t + 1, b + t)
        b = min(a + 9 - t, a + 10 - t)
        n //= 10
    print(min(a + 1, b))


main()

Submission status: Runtime Error

Solution code:
###間違っとる！！！！
#tmp="9"*(10**6)
tmp=input()
#tmp="78164062862089986280348253421170"
#tmp="314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170"
#tmp="846"
#tmp="253421170"
l=len(tmp)
#print(l)
rev=tmp[::-1]+"0"
seq_flag=False
ans=0
debug=[]
ans_arr=[]
next_bit=0
for i in range(l-1):
    num=int(rev[i])+next_bit
    next_num=int(rev[i+1])
    if not seq_flag:
        if (num<5) or (num==5 and next_num<5):
            ans+=num
            ans_arr.append(ans)
            next_bit=0
            kuri_cal=0
            continue
        seq_s=i
        seq_flag=True
        kuri_cal=10-num
        next_bit+=1
        continue
    #print(kuri_cal)
    if num<5:
        ans+=(kuri_cal+num)
        next_bit=0
        seq_flag=False
    elif num>5:
        kuri_cal+=10-num
    else:
        if next_num<5:
            ans+=(kuri_cal+num)
            next_bit=0
            seq_flag=False
        else:
            kuri_cal+=10-num
        
"""    
        
    if next_num+next_bit<5:
        ans+=(kuri_cal+2)
        ans_arr.append(ans)
        debug.append([i,ans-1])
        seq_flag=False"""
#print(ans)
last=int(tmp[0])+next_bit
#print(last)
#print(kuri_cal)
ans+=kuri_cal+min(last,11-last)
ans_arr.append(ans)
print(ans)

Submission status: Runtime Error

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 reversed(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)
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: Runtime Error

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

using ll = long long int;
constexpr int IINF = INT_MAX;

string s;
vector<vector<int> > dp;

bool solve(){
    int n;
    cin >> s;
    s.insert(s.begin(),'0');
    n = s.size();
    dp.resize(n+1,vector<int>(2,IINF/2));
    dp[0][0] = 0;
    for(int i=0;i<n;i++){
        int D = s[i]-'0';
        dp[i+1][0] = min(dp[i][0]+D, dp[i][1]+(10-D));
        dp[i+1][1] = min(dp[i][0]+D+1, dp[i][1]+(9-D));
    }
    cout << dp[n][0] << endl;
    return true;
}

int main(){
    solve();
    return 0;
}

Submission status: Runtime Error

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

using ll = long long int;
constexpr int IINF = INT_MAX;

bool solve(){
    string s;
    int n;
    cin >> s;
    s.insert(s.begin(),'0');
    n = s.size();
    vector<vector<int> > dp(n+1, vector<int>(2, IINF/2));
    dp[0][0] = 0;
    for(int i=0;i<n;i++){
        int D = s[i]-'0';
        dp[i+1][0] = min(dp[i][0]+D, dp[i][1]+(10-D));
        dp[i+1][1] = min(dp[i][0]+D+1, dp[i][1]+(9-D));
    }
    cout << dp[n][0] << endl;
    return true;
}

int main(){
    solve();
    return 0;
}

Submission status: Runtime Error

Solution code:

N = list(input())

N.reverse()

ans = 0
flag = False
L = len(N)
for i,s in enumerate(N):
    n = int(s)
    
    if flag:
        n += 1
    
    if n<5:
        ans += n
        flag = False
    elif n>5:
        ans += 10-n
        flag = True
    else:
        if i==L-1:
            ans += n
            flag = False
            
        if int(N[i+1])<5:
            ans += n
            flag = False
        else:
            ans += 10-n
            flag = True

if flag:
    ans += 1
    
print(ans)

Submission status: Runtime Error

Solution code:
N,K = map(int,input().split())
A = list(map(int,input().split()))
A = sorted(A)
mi = 0
zero = 0
for a in A:
  if a<0:
    mi+=1
  elif a==0:
    zero+=1
  else:
    break

plu = N-mi-zero
A_mi = A[0:mi:]
A_mi_rev = A_mi[::-1]
A_plu = A[mi+zero::]
A_plu_rev = A_plu[::-1]
num_mi = plu*mi
num_zero = (plu+mi)*zero+(zero*(zero-1))//2
r = max(A[-1]**2+10,A[0]**2+10)
l = A[0]*A[-1]-10
while l+1!=r:
  m = (l+r)//2
  num = 0
  if m>0:
    num+=num_mi+num_zero
    if num>=K:
      r=m
      continue
    cou=0
    for i in range(0,plu):
      while True:
        if cou>=plu-i-1:
          num+=plu-i-1
          break
        x = A_plu_rev[i]*A_plu[cou]
        if x<m:
          cou+=1
        else:
          num+=cou
          break
          
      if num>=K:
        break
    if num>=K:
      r=m
      continue
    cou = 0
    for i in range(0,mi):
      while True:
        if cou>=mi-i-1:
          num+=mi-i-1
          break
        x = A_mi[i]*A_mi_rev[cou]
        if x<m:
          cou+=1
        else:
          num+=cou
          break
          
      if num>=K:
        break

    if num>=K:
      r=m
    else:
      l=m
    
  elif m==0:
    num+=num_mi
    if num>=K:
      r=m
    else:
      l=m
  else:
    cou = 0
    for a in A_mi_rev:
      while True:
        if cou==plu:
          num+=cou
          break
        x = a*A_plu_rev[cou]
        if x<m:
          cou+=1
        else:
          num+=cou
          break
          
      if num>=K:
        break
    if num>=K:
      r = m
    else:
      l = m
      
print(l)

Submission status: Runtime Error

Solution code:

N = list(input())

N.reverse()

ans = 0
flag = False

for i,s in enumerate(N):
    n = int(s)
    
    if flag:
        n += 1
    
    if n<5:
        ans += n
        flag = False
    elif n>5:
        ans += 10-n
        flag = True
    else:
        if i==N-1:
            ans += n
            flag = False
            
        if int(N[i+1])<5:
            ans += n
            flag = False
        else:
            ans += 10-n
            flag = True

if flag:
    ans += 1
    
print(ans)

Submission status: Runtime Error

Solution code:

N = list(input())

N.reverse()

ans = 0
flag = False

for i,s in enumerate(N):
    n = int(s)
    
    if flag:
        n += 1
    
    if n<5:
        ans += n
        flag = False
    elif n>5:
        ans += 10-n
        flag = True
    else:
        if int(N[i+1])<5:
            ans += n
            flag = False
        else:
            ans += 10-n
            flag = True

if flag:
    ans += 1
    
print(ans)

Submission status: Runtime Error

Solution code:
S = input()
l = len(S)
dp = [[0]*2 for _ in range(l+1)]
for i in range(l):
  dp[i+1][0]=min(dp[i][1]+10-int(S[i]),dp[i][0]+int(S[i]))
  dp[i+1][1]=min(dp[i][1]+10-int(S[i])-1,dp[i][0]+int(S[i])+1)
print(min(dp[-1][0]+1,dp[-1][1])

Submission status: Runtime Error

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

import sys
import math
import itertools

def main():
    ns = list(map(int, sys.stdin.readline().strip()))
    ns.append(0)
    ns.reverse()

    ans = 0
    lastpay = 0

    for i in range(len(ns)):
        if lastpay == 0:
            if ns[i] <= 4 or (ns[i] == 5 and ns[i + 1] <= 4):
                ans += ns[i]
                lastpay = 0
            else:
                ans += 1 + (10 - ns[i])
                lastpay = 1
        else:
            if lastpay + ns[i] <= 4 or (lastpay + ns[i] == 5 and ns[i + 1] <= 4):
                ans += ns[i]
                lastpay = 0
            else:
                ans += 1 - 1 + (9 - ns[i])
                lastpay = 1
    #print(''.join(map(str, reversed(pay))))
    #print(''.join(map(str, reversed(charge))))
    #assert (sum(pay) + sum(charge)) == ans
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

import sys
import math
import itertools

def main():
    ns = list(map(int, sys.stdin.readline().strip()))
    ns.append(0)
    ns.reverse()

    pay = [0] * (len(ns) + 1)
    charge = [0] * (len(ns) + 1)
    for i in range(len(ns)):
        if pay[i] == 0:
            if ns[i] <= 4 or (ns[i] == 5 and ns[i + 1] <= 4):
                pay[i] = ns[i]
                charge[i] = 0
            else:
                pay[i] = 0
                pay[i + 1] = 1
                charge[i] = 10 - ns[i]
        else:
            if pay[i] + ns[i] <= 4 or (pay[i] + ns[i] == 5 and ns[i + 1] <= 4):
                pay[i] += ns[i]
                charge[i] = 0
            else:
                pay[i] = 0
                pay[i + 1] = 1
                charge[i] = 9 - ns[i]
    #print(''.join(map(str, reversed(pay))))
    #print(''.join(map(str, reversed(charge))))
    print(sum(pay) + sum(charge))

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
S = input()[::-1]
l = len(S)
dp = [[0]*2 for _ in range(l+1)]
for i in range(l):
  dp[i+1][0]=min(dp[i][0]+int(s[i]),dp[i][1]+int(s[i])+1)
  if i!=0:
    dp[i+1][1]=min(dp[i][0]+10-int(s[i]),dp[i][1]+10-(int(s[i])+1))
  else:
    dp[i+1][1]=dp[i][0]+10-int(s[i])
print(min(dp[-1][0],dp[-1][1]+1))

Submission status: Runtime Error

Solution code:
def main():
    s = input()
    s = list(reversed(s))
    s.append('0')
    dp = [[10**10 for _ in range(2)] for _ in range(10**5)]
    dp[0][0] = 0
    for i in range(len(s)):
        for j in range(2):
            x = int(s[i])
            x += j
            for a in range(10):
                ni = i+1
                nj = 0
                b = a-x
                if b < 0:
                    nj = 1
                    b += 10
                dp[ni][nj] = min(dp[ni][nj], dp[i][j]+a+b)
    print(dp[len(s)][0])


main()

Submission status: Runtime Error

Solution code:
s = input()
s = s[::-1]
s += "0"
INF = 10 ** 18
dp = [[INF for _ in range(2)] for _ in range(10 * 6 + 500)]
"""
dp[i][j] = 下からi桁目まで決めて繰り下がりがjの時の最小値, i = 0 to N, j = 0 or 1
"""
dp[0][0] = 0
n = len(s)
# print(s)

for i in range(n):
    for j in range(2):
        x = int(s[i])
        x += j
        for a in range(10):
            ni = i + 1
            nj = 0
            b = a - x
            if b < 0:
                nj = 1
                b += 10
            dp[ni][nj] = min(dp[ni][nj], dp[i][j] + a + b)

print(dp[n][0])

Submission status: Runtime Error

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

# 数値を一けたずつ配列に数値で入れる
N=list(map(int, input()))

s= [input() for _ in range(n)]

w,h,n=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(n)]

s.sort()
print(''.join(s))

s="abcABC"
s[0].upper()+s[1:].lower()

#２次元配列のスライス
import numpy as np
a=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
b=np.array(a)
c=b[1:3,1:3].tolist()
print(c)
#２次元配列初期化
z =[[0]*500 for i in range(500)]

#ゼロ埋め
s = '1234'
s_zero = s.zfill(8)

# リストのカウント
import collections
l = ['a', 'a', 'a', 'a', 'b', 'c', 'c']
c = collections.Counter(l)
for i in c.items():
    print(i)
#２次元配列SORT
l.sort(key=lambda x: x[1])


# 組合せ
from operator import mul
from functools import reduce

def cmb(n,r):
    r = min(n-r,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n - r, -1))
    under = reduce(mul, range(1,r + 1))
    return over // under

a = cmb(n, r)

# 組合せ mod 10**9+7
w,h=map(int,input().split())
n=w+h-2
r=min(w,h)-1
def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod
mod = 10**9+7 #出力の制限
N = 10**4
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, n + 1 ): # 範囲に注意
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
a = cmb(n,r,mod)
print(a%mod)


#DFS
import sys
sys.setrecursionlimit(10 ** 9) # 再帰の上限
H, W = map(int, input().split())
m = [input() for i in range(H)]
# 入力を全部くっつけて１個の文字列にして、s の位置を取得
sindex = ''.join(m).index('s')
# s　のx,yを算出
sh = sindex // W
sw = sindex % W
# 4方向検索用
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
# 探索済みリストを初期化 0=False 1=True
zz = [[0] * W for i in range(H)]
# 深さ優先探索
def dfs(h, w):
    # この,x,yは探索済みリストを1にセット
    zz[h][w] = 1

    # 四方向を順番に実行
    for i in range(4):
        nh = h + dy[i]
        nw = w + dx[i]

        # 次のx,yが枠を超えていたらスルー
        if nh < 0 or nw < 0 or nh >= H or nw >= W:
            continue
        # 次のx,yが壁だったらスルー
        if m[nh][nw] == "#":
            continue
        # 次のx,yが探索済みならスルー
        if zz[nh][nw]:
            continue
        # 次のx,yが ゴールだったらこれで終わり
        if m[nh][nw] == "g":
            print("Yes")
            sys.exit()

        # 次のx,yでDSF実行
        dfs(nh, nw)
# sの位置からdfsスタート
dfs(sh, sw)
# 途中で終わらなかったらNO
print("No")



n = int(input())
h = list(map(int, input().split()))
dp = [10 ** 9] * (n + 1)
dp[0] = 0
for i in range(n):
    for j in range(1, 3):
        if i + j < n:
            dp[i + j] = min(dp[i + j], dp[i] + abs(h[i + j] - h[i]))
print(dp[n - 1])

# くみあわせ
import itertools as it
l=[ i for i in it.product([0, 1], repeat=10)]
print(l)

# 桁指定2進数
bin_str = format(i, '08b') # iを8桁二進数

# グラフ　辺から頂点
a=[list(map(int,input().split())) for _ in range(m)]
G=[[] for _ in range(n+1)]
for j,k in a:
    G[j].append(k)
    G[k].append(j)

Submission status: Runtime Error

Solution code:
S=[int(i) for i in list(input())]
N=len(S)
ans=0
for i in range(N-1,-1,-1):
    k=S[i]
    if k>=6:
        ans+=11-k
        j=i-1
        while(j>0):
            if S[j]!=9:
                S[j]+=1
                break
            else:
                S[j]=0
                j+=1
    else:
        ans+=k
print(ans)

Submission status: Runtime Error

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
import itertools
from functools import *
from itertools import permutations,combinations,groupby
import sys
import bisect
import string
import math
import time
import random
def Golf():
    *a,=map(int,open(0))
def S_():
    return input()
def IS():
    return input().split()
def LS():
    return [i for i in input().split()]
def I():
    return int(input())
def MI():
    return map(int,input().split())
def LI():
    return [int(i) for i in input().split()]
def LI_():
    return [int(i)-1 for i in input().split()]
def NI(n):
    return [int(input()) for i in range(n)]
def NI_(n):
    return [int(input())-1 for i in range(n)]
def StoI():
    return [ord(i)-97 for i in input()]
def ItoS(nn):
    return chr(nn+97)
def LtoS(ls):
    return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[]
    g=[[] for i in range(n)]
    for i in range(E):
        inp=LI()
        org_inp.append(inp)
        if index==0:
            inp[0]-=1
            inp[1]-=1
        if len(inp)==2:
            a,b=inp
            g[a].append(b)
            if not Directed:
                g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp
            aa=(inp[0],inp[2])
            bb=(inp[1],inp[2])
            g[a].append(bb)
            if not Directed:
                g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[1]*(w+2)
    found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)]
        rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:
        print(*inp,end=end)
YN=['YES','NO']

mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
u_alp=string.ascii_uppercase
ts=time.time()
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()
 
def ran_input():
    import random
    n=random.randint(4,16)
    rmin,rmax=1,10
    a=[random.randint(rmin,rmax) for _ in range(n)]
    return n,a

show_flg=False
show_flg=True

ans=0

s=[int(i) for i in input()]
n=len(s)

dp=[[0]*2 for i in range(n+1)]
dp[0][1]=1
x,y='',''
z,w='','0'
for i in range(n):
    c=s[i]
    X,Z=x+str(c),x+str(c+1)
    Y,W=w+str(c),w+(str(c+1) if w[-1]=='0' else '0')
    Y,W=w+str(c),min(w+('0'),w+(str(c+1) if w[-1]=='0' else '0'))
    if 11-c>c:
        W=w+(str(c+1) if w[-1]=='0' else '0')
        Y=w+str(c)
    else:
        W=w+('0')
        Y=w[:-1]+str(max(int(w[-1])-1,0))+str(c)
    show((X,Y),(Z,W))
    A,B=dp[i][0],dp[i][0]
    C,D=dp[i][1],dp[i][1]
    dp[i+1][0]=min(A,B)
    dp[i+1][1]=min(C,D)
    
    x,y,z,w=X,Y,Z,W

show(dp)

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 

def main():
    N = inp()
    n = []
    while N > 0:
        n.append(N%10)
        N //= 10
    l = len(n)
    ans = 0
    for i in range(l):
        if n[i] == 10:
            n[i+1] += 1
            n[i] = 0
        if n[i] == 0:
            continue
        if n[i] <= 4:
            ans += n[i]
        elif n[i] == 5 and (i == l-1 or n[i+1] <= 4):
            ans += n[i]
        else:
            ans += 10 - n[i]
            n[i] = 0
            n[i+1] += 1
        if i == l-1:
            if n[i] == 0:
                ans += 1
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
N = int(input())
N = str(N)[::-1]
before = 0
ans = 0
ansB = 0
for i, c in enumerate(N):
    n = int(c)+before
    ansB += int(c)
    if 0 <= n < 5:
        before = 0
        ans += n
    elif n == 5:
        if i+1 == len(N):
            before = 0
            ans += n
        if int(N[i+1]) < 5:
            before = 0
            ans += n
        else:
            ans += 10-n
            before = 1
    else:
        ans += 10-n
        before = 1
print(ans + before)

Submission status: Runtime Error

Solution code:
N = list(input())
ans = 0
temp = [0] + [int(n) for n in N]
for i in reversed(range(1, len(N)+1)):
    if temp[i] < 5 or (temp[i] == 5 and temp[i+1] < 4):
        ans += temp[i]
    else:
        temp[i+1] += 1
        ans += (10 - temp[i])
        temp[i] = 0
ans += temp[0]
print(ans)

Submission status: Runtime Error

Solution code:
s = list(map(int,input()))
L = len(s)
o = s[0]
p = 11-s[1]
for i in range(1,L):
    n = s[i]
    np = min(o+n,p+n)
    d = min(p+9-n,o+11-n)
    o = np
    p = d
print(min(o,p))

Submission status: Runtime Error

Solution code:
prev = 0
for i in range(len(N)):
  if 0 <= int(N[i]) + prev < 5:
    count += int(N[i]) + prev
    prev = 0
  elif 6 <= int(N[i]) + prev <= 9:
    count += 10 - (int(N[i]) + prev)
    prev = 1
  elif int(N[i]) + prev == 10:
    prev = 1
  else:
    if i < (len(N) - 1) and int(N[i+1]) < 5:
      count += 5
      prev = 0
    else:
      count += 5
      prev = 1
count = count + prev

Submission status: Runtime Error

Solution code:
N = input()
count = 0
prev = 0
for i in range(len(N)):
  if 0 <= int(N[i]) + prev < 5:
    count += int(N[i]) + prev
    prev = 0
  elif 6 <= int(N[i]) + prev <= 9:
    count += 10 - (int(N[i]) + prev)
    prev = 1
  elif int(N[i]) + prev == 10:
    prev = 1
  else:
    if i < len(N) and int(N[i+1]) < 5:
      count += 5
    else:
      count += 5
      prev = 1
count = count + prev
print(count)

Submission status: Runtime Error

Solution code:
from functools import lru_cache
 
n = int(input())
 
@lru_cache(None)
def F(n):
    assert n >= 0
    if n <= 0:
        if n <= 5:
            return n
        return 11 - n
    
    res = 0
    q, r = divmod(n, 10)
    if r > 5:
        res += 10 - r + F(q + 1)
    elif r <= 5:
        res += r + F(q)
    return res
 
print(F(n))

Submission status: Runtime Error

Solution code:
from itertools import groupby

def fivefunction(num):
    if num>=5:
        return 1
    else:
        return 0

N=input()
A=[int(N[i]) for i in range(0,len(N))]
fiveonlyzone=0
for i in range(0,len(N)):
    if i==0:
        if A[i]==5 and A[i+1]<5:
            fiveonlyzone+=1
    elif i==len(N)-1:
        if A[i-1]<5 and A[i]==5:
            fiveonlyzone+=1
    else:
        if A[i-1]<5 and A[i]==5 and A[i+1]<5:
            fiveonlyzone+=1

Ndigitsum=sum(A)
data=[fivefunction(A[i]) for i in range(0,len(N))]
Adigitsum=0
for i in range(0,len(N)):
    if fivefunction(A[i])==0:
        Adigitsum+=A[i]
X=groupby(data)
zone=0
digit=0
for key,group in X:
    g=len(list(group))
    if key==1:
        zone+=1
        digit+=g
print(9*digit+2*zone+2*Adigitsum-Ndigitsum-fiveonlyzone)

Submission status: Runtime Error

Solution code:
from itertools import groupby

def fivefunction(num):
    if num>=5:
        return 1
    else:
        return 0

N=input()
A=[int(N[i]) for i in range(0,len(N))]
fiveonlyzone=0
for i in range(0,len(N)):
    if i==0:
        if A[i]==5 and A[i+1]<5:
            fiveonlyzone+=1
    elif i==len(N)-1:
        if A[i-1]<5 and A[i]==5:
            fiveonlyzone+=1
    else:
        if A[i-1]<5 and A[i]==5 and A[i+1]<5:
            fiveonlyzone+=1

Ndigitsum=sum(A)
data=[fivefunction(A[i]) for i in range(0,len(N))]
Adigitsum=0
for i in range(0,len(N)):
    if fivefunction(A[i])==0:
        Adigitsum+=A[i]
    else:
        A[i]=0
X=groupby(data)
zone=0
digit=0
for key,group in X:
    g=len(list(group))
    if key==1:
        zone+=1
        digit+=g
print(zone,digit,A)
print(9*digit+2*zone+2*Adigitsum-Ndigitsum-fiveonlyzone)