#include #include #include using namespace std ; typedef long long ll ; string s ; const int INFTY = 1000000 ; ll m ; map cache ; int recur(int zeros, int left, int right, int cin, int cout, int lead) { ll key = zeros + m * (left + m * (right + m * (cin + 2 * (cout + 3 * lead)))) ; if (cache.find(key) != cache.end()) return cache[key] ; int r = INFTY ; if (zeros > 0) { int dig = s[left] - '0' ; if (dig == 0 && cout != 1) r = recur(zeros-1, left+1, right, cin, 0, lead) ; if (cout != 0) { r = min(r, 10 - dig + recur(zeros-1, left+1, right, cin, 0, lead)) ; r = min(r, 9 - dig + recur(zeros-1, left+1, right, cin, 1, lead)) ; } } else if (left == right) { int dig = s[left] - '0' + cin ; if (dig == 10 && cout == 0) r = INFTY ; else if (cout == 1) r = 10 - dig ; else if (dig == 0 && lead) r = 1 ; else r = 0 ; } else if (left > right) { if ((cin == 0 && cout != 1) || (cin == 1 && cout != 0)) r = 0 ; } else { int ldig = s[left] - '0' ; int rdig = s[right] - '0' + cin ; for (int linc=0; linc<=10; linc++) for (int rinc=0; rinc<10; rinc++) if ((ldig + linc) % 10 == (rdig + rinc) % 10 && ((cout != 0 && (ldig + linc >= 10)) || (cout != 1 && (ldig + linc < 10)))) { if (lead && (ldig + linc) % 10 == 0) continue ; if (linc < 10) r = min(r, linc+rinc+ recur(zeros, left+1, right-1, (rdig+rinc > 9 ? 1 : 0), 0, 0)) ; if (linc > 0) r = min(r, linc-1+rinc+ recur(zeros, left+1, right-1, (rdig+rinc > 9 ? 1 : 0), 1, 0)) ; } } cache[key] = r ; return r ; } int main() { cin >> s ; m = s.size() + 2 ; int r = 10 * s.size() ; for (int zeros=0; zeros<=s.size(); zeros++) { int t = recur(zeros, 0, s.size()-1, 0, 2, 1) ; // cout << "For zeros " << zeros << " got " << t << endl ; r = min(r, t) ; } cout << r << endl ; }