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:
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using uint = unsigned int;
using pcc = pair<char, char>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<double, double>;
using tuplis = array<ll, 3>;
template<class T> using pq = priority_queue<T, vector<T>, greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const int MOD=1000000007;
const int MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.1415926535897932;
const ll four[] = {0, 1, 0, -1, 0};
const ll eight[] = {0, 1, 1, 0, -1, -1, 1, -1, 0};
#define overload4(_1,_2,_3,_4,name,...) name
#define overload3(_1,_2,_3,name,...) name
#define rep1(n) for(ll i=0;i<n;++i)
#define rep2(i,n) for(ll i=0;i<n;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(n) for(ll i=(n)-1;i>=0;i--)
#define rrep2(i,n) for(ll i=(n)-1;i>=0;i--)
#define rrep3(i,a,b) for(ll i=(b)-1;i>=(a);i--)
#define rrep4(i,a,b,c) for(ll i=a+(b-a-1)/c*c;i>=a;i-=c)
#define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__)
#define each(i,...) for(auto&& i:__VA_ARGS__)
#define all1(i) begin(i),end(i)
#define all2(i,a) begin(i),begin(i)+a
#define all3(i,a,b) begin(i)+a,begin(i)+b
#define all(...) overload3(__VA_ARGS__,all3,all2,all1)(__VA_ARGS__)
#define rall1(i) (i).rbegin(),(i).rend()
#define rall2(i,k) (i).rbegin(),(i).rbegin()+k
#define rall3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rall(...) overload3(__VA_ARGS__,rall3,rall2,rall1)(__VA_ARGS__)
#define sum(...) accumulate(all(__VA_ARGS__),0LL)
#define dsum(...) accumulate(all(__VA_ARGS__),0.0L)
#define elif else if
#define unless(a) if(!(a))
#define mp make_pair
#define mt make_tuple
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define SORT(a) sort(all(a))
#define REVERSE(a) reverse(all(a))
#define UNIQUE(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define vec(type,name,...) vector<type> name(__VA_ARGS__)
#define VEC(type,name,size) vector<type> name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template<class T> auto max(const T& a){ return *max_element(all(a)); }
template<class T> auto min(const T& a){ return *min_element(all(a)); }
ll gcd(ll a, ll b){ while(b){ ll c = b; b = a % b; a = c; } return a; }
ll lcm(ll a, ll b){ if(!a || !b) return 0; return a * b / gcd(a, b); }
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
vector<pll> factor(ull x){ vector<pll> ans; for(ll i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ll i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }
template<class T> unordered_map<T, ll> press(vector<T>& a){ auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); unordered_map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
template<class T> map<T, ll> press_map(vector<T>& a){ auto b = a; sort(all(b)); b.erase(unique(all(b)), b.end()); map<T,ll> ans; rep(b.size()) ans[b[i]] = i; each(i, a) i = ans[i]; return ans; }
int scan(){ return getchar(); }
void scan(int& a){ scanf("%d", &a); }
void scan(unsigned& a){ scanf("%u", &a); }
void scan(long& a){ scanf("%ld", &a); }
void scan(long long& a){ scanf("%lld", &a); }
void scan(unsigned long long& a){ scanf("%llu", &a); }
void scan(char& a){ do{ a = getchar(); }while(a == ' ' || a == '\n'); }
void scan(float& a){ scanf("%f", &a); }
void scan(double& a){ scanf("%lf", &a); }
void scan(long double& a){ scanf("%Lf", &a); }
void scan(vector<bool>& a){ for(unsigned i = 0; i < a.size(); i++){ int b; scan(b); a[i] = b; } }
void scan(char a[]){ scanf("%s", a); }
void scan(string& a){ cin >> a; }
template<class T> void scan(vector<T>&);
template<class T, size_t size> void scan(array<T, size>&);
template<class T, class L> void scan(pair<T, L>&);
template<class T, size_t size> void scan(T(&)[size]);
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
template<class T> void scan(deque<T>& a){ for(auto&& i : a) scan(i); }
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i); }
template<class T, class L> void scan(pair<T, L>& p){ scan(p.first); scan(p.second); }
template<class T, size_t size> void scan(T (&a)[size]){ for(auto&& i : a) scan(i); }
template<class T> void scan(T& a){ cin >> a; }
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){ scan(head); in(tail...); }
void print(){ putchar(' '); }
void print(bool a){ printf("%d", a); }
void print(int a){ printf("%d", a); }
void print(unsigned a){ printf("%u", a); }
void print(long a){ printf("%ld", a); }
void print(long long a){ printf("%lld", a); }
void print(unsigned long long a){ printf("%llu", a); }
void print(char a){ printf("%c", a); }
void print(char a[]){ printf("%s", a); }
void print(const char a[]){ printf("%s", a); }
void print(float a){ printf("%.15f", a); }
void print(double a){ printf("%.15f", a); }
void print(long double a){ printf("%.15Lf", a); }
void print(const string& a){ for(auto&& i : a) print(i); }
template<class T> void print(const vector<T>&);
template<class T, size_t size> void print(const array<T, size>&);
template<class T, class L> void print(const pair<T, L>& p);
template<class T, size_t size> void print(const T (&)[size]);
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T> void print(const deque<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size>& a){ print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L>& p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> void print(const T (&a)[size]){ print(a[0]); for(auto i = a; ++i != end(a); ){ putchar(' '); print(*i); } }
template<class T> void print(const T& a){ cout << a; }
int out(){ putchar('\n'); return 0; }
template<class T> int out(const T& t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
#ifdef DEBUG
void err(){ putchar('\n'); }
template<class T> void err(const T& t){ print(t); putchar('\n'); }
template<class Head, class... Tail> void err(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); }
#else
template<class... T> void err(const T&...){}
#endif
int first(bool i = true){ return out(i?"first":"second"); }
int yes(bool i = true){ return out(i?"yes":"no"); }
int Yes(bool i = true){ return out(i?"Yes":"No"); }
int No(){ return out("No"); }
int YES(bool i = true){ return out(i?"YES":"NO"); }
int NO(){ return out("NO"); }
int Yay(bool i = true){ return out(i?"Yay!":":("); }
int possible(bool i = true){ return out(i?"possible":"impossible"); }
int Possible(bool i = true){ return out(i?"Possible":"Impossible"); }
int POSSIBLE(bool i = true){ return out(i?"POSSIBLE":"IMPOSSIBLE"); }
void Case(ll i){ printf("Case #%lld: ", i); }




signed main(){
    STR(s);
    REVERSE(s);
    ll n=s.size();
    each(i,s)i-='0';
    ll ans=sum(s);
    s.push_back(0);
    rep(n)if(s[i]>=6||s[i]==5&&s[i+1]>=5){
        ans+=11-2*s[i];
        s[i+1]++;
    }
    out(ans);
}

Submission status: Runtime Error

Solution code:
n = str(input())[::-1]
n = "0" + n
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: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(10**7)

G = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
N = input()
len_N = len(N)
dp = [[-1] * 2 for _ in range(len_N + 1)]
INF = 10**9


def dfs(i, j):
    if i < 0:
        if j == 0:
            return 0
        else:
            return 1
    
    if 0 <= dp[i][j]:
        return dp[i][j]
    
    res = INF
    for d in range(10):
        n = int(N[i]) + j
        sm = G[d]
        if d < n:
            sm += dfs(i - 1, 1) + G[10 + d - n]
        else:
            sm += dfs(i - 1, 0) + G[d - n]
        res = min(res, sm)
    
    dp[i][j] = res
    return res


def solve():
    ans = dfs(len_N - 1, 0)
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
G = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
N = input()
len_N = len(N)
dp = [[-1] * 2 for _ in range(len_N + 1)]
INF = 10**9


def dfs(i, j):
    if i < 0:
        if j == 0:
            return 0
        else:
            return 1
    
    if 0 <= dp[i][j]:
        return dp[i][j]
    
    res = INF
    for d in range(10):
        n = int(N[i]) + j
        sm = G[d]
        if d < n:
            sm += dfs(i - 1, 1) + G[10 + d - n]
        else:
            sm += dfs(i - 1, 0) + G[d - n]
        res = min(res, sm)
    
    dp[i][j] = res
    return res


def solve():
    ans = dfs(len_N - 1, 0)
    print(ans)


if __name__ == '__main__':
    solve()

Submission status: Runtime Error

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 and Num[i+1] >= 5)
    else:
        S += 10 - n
        up = True
if up:
    S += 1
print(S)

Submission status: Runtime Error

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

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]

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

sum=sum_otsuri+sum_pay
print(sum)

Submission status: Runtime Error

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 and Num[i+1] >= 5
    else:
        S += 10 - n
        up = True
if up:
    S += 1
print(S)

Submission status: Runtime Error

Solution code:
from functools import lru_cache

n = list(map(int, list(input())))
m = len(n)

@lru_cache(10**10)
def rec(keta, tight):
    if keta == m:
        if tight:
            return 1
        else:
            return 0
    tmp = float("inf")
    for i in range(10):
        if tight:
            if i == 0:
                tmp = min(tmp, rec(keta+1, True)+9-n[keta])

            elif i <= n[keta]:
                tmp = min(tmp, rec(keta+1, True)+i+10+i-1-n[keta])
            else:
                tmp = min(tmp, rec(keta+1, False)+i+i-1-n[keta])
        else:
            if i < n[keta]:
                tmp = min(tmp, rec(keta+1, True)+i+(10+i)-n[keta])
            else:
               tmp = min(tmp, rec(keta+1, False)+i+i-n[keta])
    return tmp

ans = rec(0, False)
print(ans)

Submission status: Runtime Error

Solution code:
N = input()
l = len(N)
#A = [0]*(N+2)
ans=0
def che(N,a):
    #l = len(N)
    #b+=1
    k=int(N[0])
    if(k>=5):
        a+=1+(10-k)-1
    else:
        a+=k
    if(l!=0):
        che(N[1:l],a)


a=0
for i in range(l):
    k=int(N[i])
    #print(k)
    if(k>=6):
        a+=1+(10-k)
    else:
        """
        if k==5:
            for j in range(i,l):
                c=0
                if(int(N[j])!=0):
                    c+=1
            if c>0:
                a+=1+(10-k)
            else:
                a+=5
        """
        else:
            a+=k
    #print(a)
print(a)

Submission status: Runtime Error

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

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

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

Submission status: Runtime Error

Solution code:
def main():
    N = list(input()[::-1])
    n = "".join(N)[::-1]
    if len(N) > 101:
        tmp = N[:101]
        over = N[101:]
        for i in range(len(over)):
            tmp[100] += over[i]*10**(i+1)
        tmp = list(map(int,tmp))
    else:
        tmp = list(map(int,N)) + [0]*(101-len(N))
    num = []
    for i in range(len(tmp)-1):
        if tmp[i] > 5:
            num.append("0")
            tmp[i+1] += 1
        else:
            num.append(str(tmp[i]))
    num.append(str(tmp[-1]))
    ans = sum(list(map(int,num)))
    t1 = int("".join(num)[::-1])
    t2 = int(n)
    tmp = sum(list(map(int,list(str(t1-t2)))))
    print(ans+tmp)
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
N = input()

t = 0
for i in N:
    num = int(i).reverse()
    if 1<=num<=5:
        flag = False
        t += num
    elif 5<num:
        flag = True
        if flag:
            t += 10 - num
        else:
            t += 1+(10-num)
    else:
        continue

print(t)

Submission status: Runtime Error

Solution code:
import math
N = int(input())

n = N
ans = 0
n_dig = math.floor(math.log10(N)) + 1 # Nの桁数
mai = [0] * n_dig # 枚数

for i in range(n_dig):
    d = n % 10
    n //= 10
    if d < 1 + 10 - d:
        mai[i] = d
    else:
        mai[i] = d - 10 # おつり
        mai[i+1] = 1

    ans += min(d, 1 + 10 - d)
    if n == 0: break

print(sum([abs(m) for m in mai]))

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 10 - 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:
#import pysnooper
#import numpy
#import os,re,sys,operator
#from collections import Counter,deque
#from operator import itemgetter,mul
#from itertools import accumulate,combinations,groupby,combinations_with_replacement,permutations
from sys import stdin,setrecursionlimit
#from bisect import bisect_left,bisect_right
#from copy import deepcopy
#import heapq
#import math
#import string
#from time import time
#from functools import lru_cache,reduce
#from math import factorial,hypot
#import sys
#from fractions import gcd
setrecursionlimit(10**6+1)
input=stdin.readline

INF=2<<32
n=input().rstrip()
g=[0,1,2,3,4,5,6,7,8,9,1]
dp=[[-1]*2 for _ in range(1000001)]
r=range(10)
def rec(i,j):
    res=INF
    if i<0:
        return 0 if j==0 else 1
    if dp[i][j]>=0: return dp[i][j]
    for a in r:
        now=int(n[i])+j
        t=g[a]
        if a<now: t+=rec(i-1,1)+g[10+a-now]
        else: t+=rec(i-1,0)+g[a-now]
        res=min(res,t)
    dp[i][j]=res
    return dp[i][j]

print(rec(len(n)-1,0))

Submission status: Runtime Error

Solution code:
from functools import lru_cashe

n = int(input())

@lru_cashe(None)
def F(n):
    assert n >= 0
    if n <= 0:
        if n <= 5:
            return n
        return 10 - 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:
n=input()
price=int(n) 
digit=len(n) 
answer=0 
dp=[0]*(digit-1) 
if n[0]=="9":
    dp.append(0)
if int(n[-1])<=5: 
    dp[0]=int(n[-1]) 
else:
    dp[0]=10-int(n[-1]) 
    price+=10 
    n=str(price)
    digit=len(n) 
for i in range(digit-2): 
    dp[i+1]=dp[i]+min(int(n[-(i+2)]),10-int(n[-(i+2)]))
dp[-1]+=min(int(n[0]),10-int(n[0]))
if n[0]=="9":
    dp[-1]+=1
    if price<=95:
        dp[-1]+=1
print(dp[-1])

Submission status: Runtime Error

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

Solution code:
n_r = list(map(int,list(n)[::-1]))
for i in range(len(n)):
    if n_r[i] >= 10:
        n_r[i] -= 10 
    elif n_r[i] > 5:
        if len(n_r) < i+1+1:
            n_r.append(0)
        n_r[i+1] += 1
        n_r[i] = 0
a = sum(map(int,list(n)))
tmp = map(int,list(str(int("".join(list(map(str,n_r[::-1]) ) ) ) - int(n))))
b = sum(n_r[::-1]) + sum(tmp)

if a > b:
    print(b)
else:
    print(a)

Submission status: Runtime Error

Solution code:
import math
n=int(input())
ans = 0
for i in range(100+1):
  k=int(math.log10(n))

  for i in range(10):
    if (10**k)*(i+1) >= n:
      j = i
      break
ans=+=j
n -= (10**k)*(j+1)
if n==0:
  print(ans)

Submission status: Runtime Error

Solution code:
#import sys
#input = sys.stdin.readline
def main():
    S = [ int(x) for x in input()]
    ans = 0
    N = len(S)
    l = 0
    r = 1
    d = dict()
    d[0] = 0
    d[1] = 1
    d[2] = 2
    d[3] = 3
    d[4] = 4
    d[5] = 5
    d[6] = 4
    d[7] = 3
    d[8] = 2
    d[9] = 1
    for i in range(N):
        if S[i] >= 5 and i < N-1:
            continue
        for s in range(l,i+1):
            if s == l and S[s] == 9:
                ans += 2
                continue
            ans += d[s]
        l = i
    print(ans)
            
if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
s = [0] + list(map(int, input()))

def f(i):
    if i < 0:
        return
    if s[i] == 9:
        s[i] = 0
        f(i-1)
    else:
        s[i] = s[i] + 1
    return

r = 0
i = len(s)
while i != 0:
    i -= 1
    if s[i] > 5:
        r += 10-s[i]
        s[i] = 0
        f(i-1)
    if s[i] == 5:
        if s[i-1] >= 5:
            r += 10-s[i]
            s[i] = 0
            f(i-1)
print(r+sum(s))

Submission status: Runtime Error

Solution code:
S = list(map(int,list(input())))
ans = 0
di = {1:1,2:2,3:3,4:4,5:5,6:4,7:3,8:2,9:1,0:0}
for i in range(len(S)-1,-1,-1):
    ans += di[S[i]]
'''
    if S[i] >= 6:
        if i == 0:
            ans += 1
        elif S[i-1] != 0:
            S[i-1] = (S[i-1]+1)%10
'''
if (S[0] >= 6 and S[min(1,len(S)-1)] <5) or (S[min(1,len(S)-1)] >= 6 and S[0]<5:
    ans += 1
print(ans)

Submission status: Runtime Error

Solution code:
import math
Nmin=1000
memo = {}
memo[1]= 1
memo[2]= 2
memo[3]= 3
memo[4]= 4
memo[5]= 5
memo[6]= 5
memo[7]= 4
memo[8]= 3
memo[9]= 2

def num(N):
    n = 0
    while(N>0):
        index = int(math.log10(N))
        a = int(N/math.pow(10,index))
        n += memo[a]
        N -= a*pow(10,index)

    return(n)

N = int(input())
print(num(N))

Submission status: Runtime Error

Solution code:
s = input()
sr = s.reverse()
count = 0
for i in range(len(sr)-1):
    if sr[i]>=5:
        count += 10-sr[i]
        sr[i+1] += 1
    else:
        count += sr[i]
if sr[len(sr)-1] >=5:
    count += 1
    count += 10- sr[len(sr)-1]
else:
    count += sr[len(sr)-1]
print(count)

Submission status: Runtime Error

Solution code:
N = int(input())
cnt = 0
L = len(str(N))
for i in range(L+1):
  if i == L and L ==len(str(N)):
    break
    
  if int(str(N)[-1-i]) ==5 :
    cnt+=5
    if int(str(N)[-1-i-1]) >= 5:
      N += int(10**(i+1))
    
  if  0 < int(str(N)[-1-i]) <5:
    cnt += int(str(N)[-1-i])     
  elif int(str(N)[-1-i]) > 5:
    N += int(10**(i+1))
    cnt += 10-int(str(N)[-1-i])

print(cnt)

Submission status: Runtime Error

Solution code:
str = list(input())

target = reversed(str)

res = 0
c = 0
ff = 0
for i in target:
  if (int(i)+c < 6):
    res += int(i)+c
    c = 0
  else:
    res += 10-(int(i)+c)
    c = 1
  	res -= ff
  if (int(i)+c == 5):
    ff += 1
  else:
    ff = 0
if (c == 1):
  res += 1
print(res)

Submission status: Runtime Error

Solution code:
s = [0] + list(map(int, input()))

def f(i):
    if i < 0:
      return
    if s[i] == 9:
        s[i] = 0
        f(i-1)
    else:
        s[i] = s[i] + 1
    return

r = 0
i = len(s)
while i != 0:
    i -= 1
    if s[i] > 5:
        r += 10-s[i]
        s[i] = 0
        f(i-1)
    if s[i] == 5:
        if s[i-1] >= 5:
            r += 10-s[i]
            s[i] = 0
            f(i-1)
print(r+sum(s))

Submission status: Runtime Error

Solution code:
from itertools import combinations
 
a,b = input().split()
arr = list(map(int,input().split()))
les = list(combinations(arr,2))
out = [(x*y)for x,y in les]
out.sort()
 
print(out[int(b)-1])

Submission status: Runtime Error

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

n = n[::-1]
me_s = 0
last = False
five = 0
for i in range(len(n)):
    a = n[i]
    if last:
        a += 1


    if a == 5:
        five += 1
    else:
        if five >= 2:
            a += 1
        elif five == 1:
            if a >= 6:
                a += 1
            else:
                me_s += 5 * (10 ** (i - 1))
        if a >= 6:
            last = True
        else:
            last = False
            me_s += a * (10 ** i)
        five = 0


if last:
    me_s += 10 ** len(n)

me = sum(list(map(int, list(str(me_s)))))


tenninn = sum(list(map(int, list(str(me_s - n_)))))


print(me + tenninn)

Submission status: Runtime Error

Solution code:
n = list(map(int, list(input())))
ans = 0
c_in = 0
q = 0


def carry(x, i, q):
    if x[i] <= 8:
        x[i] += 1
    else:
        x[i] = 0
        if x[i] == x[0]:
            x[i] = 0
            q += 1
        else:
            carry(x, i-1, q)


while len(n) > 0:
    s = n.pop()
    if 0 <= s <= 5:
        ans += s
        if c_in:
            c_in = 0
    elif 6 <= s <= 9:
        ans += 10 - s
        c_in = 1
        carry(n, -1, q)
    print(s, ans)

ans += q
print(ans)

Submission status: Runtime Error

Solution code:
n = input()
intn = int(n)
lenn = len(n)
def keta_sum(n):
    sum = 0
    while n>0:
        sum += n%10 #対象の桁を加算
        n = n//10 # 次の桁をみる
    return(sum)
min_ = float('inf')
for i in  range(lenn):
    wai = n[:i] + str(int(n[i])+1) + '0'*(lenn-i)
    intwai = int(wai)
    ketawai = keta_sum(intwai)
    anata = n - intwai
    ketaanata = keta_sum(anata)
    if ketawai + ketaanata < min_:
        min_ = ketawai + ketaanata
print(min_)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
import sys

def main():
    input = sys.stdin.readline
    n=input()
    ans=0
    rn=[]
    for i in reversed(range(len(n))):
        rn.append(int(n[i]))

    i=0
    while i<len(rn):
        tmp=rn[i]
        if tmp<=5:
            ans+=tmp
            i+=1
        else:
            tmp2=""
            tmp3=0
            while(i<len(rn)):
                if rn[i]>5:
                    tmp2=int(str(rn[i])+str(tmp2))
                    tmp3+=1
                    ans+=tmp
                else:
                    break
                i+=1
            ans=ans+1-rn[i-1]+(10**tmp3-tmp2)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from fractions import gcd
from functools import reduce
from math import ceil, gcd
import sys
def solve(N):
    S = str(N)
    S = list(reversed(S))
    ans = 0
    for x in S:
        x = int(x)
        if x == 5:
            ans += 5
        elif x == 0:
            ans -= 1
            
        if 10 - x > x:
            ans += x + 1
        
        else:
            ans += 10-x

    return ans

def main():
    # N = int(input())
    # A = [int(x) for x in input().split()]
    # N = int(sys.stdin.readline().rstrip())
    # A = [int(sys.stdin.readline().rstrip().split())]
    # read = sys.stdin.buffer.read
    
    # N,*A = map(int,read().split())
    N = int(input())
    ans = solve(N)
    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

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 i > 100:
        res += (i-100)*p
        add = False
        continue

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

Solution code:
# 入力が10**5とかになったときに100ms程度早い
import sys
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_matrix(H):
    '''
    H is number of rows
    '''
    return [list(map(int, read().split())) for _ in range(H)]


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols

    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])

    return ret


from functools import lru_cache
import sys
sys.setrecursionlimit(1 << 25)

N = read()[:-1]
siharai = ''


@lru_cache(None)
def F(n: str):
    '''
    支払う金額を返す。再帰関数
    '''
    global siharai
    # 終了条件
    if len(n) < 10 and int(n) < 5:
        siharai += str(n)
        return 0

    # 桁dpもどき
    # 1の位が4以下ならそのまま紙幣で支払うのが得→自身をそのまま答えに採用
    # 6以上ならばお釣り狙いのほうが得→自身は0にセットして、上位桁を+1する
    # 5ちょうどのときは？ #お釣りもそのまま払っても同じ。だけど上位 お釣り狙いだと上の桁が多くなって支払う金額が増える可能性がある？
    # 5ピッタリのときに上位桁に+1すると悪くなる場合が存在する 455 とは 15にってしまう
    # 5ピッタリのときはどうするのがよいのか？
    q, r = n[:-1], n[-1]
    if r == '5':
        qq, rr = q[:-1], q[-1]
        if int(rr) < 5:
            # そのまま
            joint = '5'
            F(q)
        else:
            joint = '0'
            F(str(int(q) + 1))
    elif int(r) < 5:
        joint = r
        F(q)
    else:
        joint = '0'
        F(str(int(q) + 1))
    siharai += joint


F(N)
siharai = int(siharai)
oturi = siharai - int(N)

ans = 0
for a in str(siharai) + str(oturi):
    ans += int(a)

print(ans)

Submission status: Runtime Error

Solution code:
d = input()
len_d = len(d)
res = 0
up_flg=False
for i in range(len_d):
  use_i = -i - 1
  use_digit = int(d[use_i])
  if up_flg:
    use_digit += 1
    up_flg = False
    if use_digit == 10:
      use_digit = 0
      up_flg = True
  if use_digit > 5:
    res += 10 - use_digit
    up_flg = True
  elif use_digit == 5:
    next_digit = int(d[use_i-1])
    if next_digit >= 5:
      res += 10 - use_digit
      up_flg = True
    else:
      res += use_digit
  else:
    res += use_digit
if up_flg:
  res += 1
print(res)

Submission status: Runtime Error

Solution code:
ans1 = len(N)*5
ans2 = len(N)*5

A = 0
for i in N:
    ans1 -= abs(5-int(i))
    ans2 -= abs(5-int(i))
    if A * (5-int(i)) > 0:
        ans1 += 1
        ans2 -= 1
    elif A * (5-int(i)) < 0:
        ans1 -= 1
        ans2 += 1
    
    if 5-int(i)>0:
        A = 1
    elif 5 - int(i)<0:
        A = -1
    else:
        A = 0
print(int((ans1+ans2)/2))

Submission status: Runtime Error

Solution code:
# coding: utf-8
import copy
N=int(input())
m=len(str(N))
N1=copy.copy(N)
m2=copy.copy(m)

n=str(N)
ans=0
for i in range(m):
    m1=int(n[i])
    if m1<=5:
        ans+=m1
    else:
        ans+=10-m1

if m<=2:
    ans=(int(n[0])+int(n[1]),(int(n[0])+1)%10+10-int(n[1))
    print(ans)
else:
    print(ans)
#print(ans)