#include #include using namespace std; #define rep(i,n) for(long long i = 0; i < (long long)(n); i++) #define pb push_back template bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); } using ll = long long; using vll = vector; unordered_map memo; ll pay[10] = {0, 1, 2, 3, 2, 1, 2, 3, 3, 2}; vll p10; ll dfs(ll n) { n = abs(n); if (memo.count(n)) return memo[n]; if (!n) return 0; vll nd; ll only_msd = 1; // n = a*10^kなるa, kが存在するか ll n_tmp = n; for (; n_tmp ; n_tmp /= 10) nd.pb(n_tmp % 10); rep(i, nd.size()-1) only_msd &= !nd[i]; ll msd = nd.back(); // 最大桁 ll d = p10[nd.size()-1]; // 桁数 ll ret = 4e18; chmin(ret, pay[msd] + dfs(n - msd * d)); if (!only_msd) chmin(ret, pay[msd==9?1:msd+1] + dfs((msd + 1) * d - n)); return memo[n] = ret; } int main(void) { ll n; cin >> n; assert(1<=n&&n<=1e18); for (ll b = 1, i = 0; i < 18; b*=10, i++) p10.pb(b); cout << dfs(n) << endl; return 0; }