#include #include using namespace std; using i64 = int64_t; constexpr i64 inf = 987654321987654321LL; // 0 1 2 3 4 5 6 7 8 9 vector v = {0, 1, 2, 3, 4, 1, 2, 3, 4, 5}; int cmp(int x, int y) { if(x < y) { return 0; } if(x == y) { return 1; } return 2; } i64 f(string s) { s = "0" + s; int n = static_cast(s.size()); // dp[未満/丁度/超過][繰り上がったか] := 最小枚数 vector> dp(3, vector(2, inf)); dp[1][0] = 0; for(int i=n-1; i>=0; --i) { vector> ndp(3, vector(2, inf)); for(int flag=0; flag<3; ++flag) { for(int carry=0; carry<2; ++carry) { if(dp[flag][carry] == inf) { continue; } for(int yd=0; yd<10; ++yd) { // X - N を決める int nflag = cmp(yd, s[i] - '0'); if(nflag == 1) { nflag = flag; } int xd = (yd + carry + (s[i] - '0')) % 10, // X が決まる ncarry = (yd + carry + (s[i] - '0')) / 10; ndp[nflag][ncarry] = min(ndp[nflag][ncarry], dp[flag][carry] + v[yd] + v[xd]); } } } dp = ndp; } i64 res = inf; for(int flag=0; flag<2; ++flag) { res = min(res, dp[flag][0]); } return res; } int main(void) { string s; cin >> s; i64 res = f(s); printf("%ld\n", res); return 0; }