#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define f(i, x, y) for(int i = x; i < y; i++)
#define all(X) X.begin(), X.end()
#define int long long
const  int mod = 1e9 + 7;
const int inf = 1e18;
using namespace std;
unordered_map<int, int> m;

int get(int n)
{
    if(n == 0)
        return 0;
    if(m[n] == -1)
        return inf;
    else if(m[n] > 0)
        return m[n];

    int i = 1, c = 1;
    while(i < n)
    {
        i = i * 10 + 1;
        c++;
    }
    m[n] = -1;
    
    if(i == n)
    {
        m[n] = c;
        return c;
    }
    
    int x = get(abs(i/10 - n)) + c-1, y = get(abs(i - n)) + c;
    m[n] = min(x, y);
    
    return m[n];
}

main()
{
    fastread;
    int n; cin>>n;

    cout<<get(n);
    
}

Generated URL:

Output:

13
Report Bug