#include <bits/stdc++.h>
using namespace std ;
typedef long long ll ;
struct node {
ll num ;
bool where ;
bool operator<(const node& other) const {
return num < other.num || (num == other.num && where < other.where);
}
int get () {
if ( num < 100000000 ) return 1 ;
else {
ll x = num ;
int ans = 9 ;
while ( x ) {
if ( x%10 == 0 ) return ans ;
x /= 10 , ans-- ;
}
}
return 0 ;
}
}s,e ;
node make ( ll a , bool b ) {
node x ;
x.num = a , x.where = b ;
return x ;
}
ll change ( ll num , ll x , ll y ) {
if ( x == y ) return num ;
if ( x > y ) swap ( x , y ) ;
x = 9-x ;
y = 9-y ;
ll px = pow (10,x) , py = pow(10,y) ;
ll dx = (num/px)%10 , dy = (num/py)%10 ;
return num+px*(dy-dx)+py*(dx-dy) ;
}
queue <node> q ;
map <node,ll> mp ;
ll n ;
int main () {
ios::sync_with_stdio(0) , cin.tie(0) , cout.tie(0) ;
cin >> n ;
s = {n,0} , e = {123804765,1} ;
q.push(s) , q.push(e) , mp[s] = 0 , mp[e] = 1 ;
while ( q.size() ) {
node now = q.front() ;
q.pop() ;
if ( mp[make(now.num,!now.where)] ) {
cout << mp[make(now.num,!now.where)]+mp[now]-1 ;
return 0 ;
}
ll _0 = now.get() ;
if ( _0 > 3 ) {
if ( mp[make(change(now.num,_0-3,_0),now.where)] != 0 ) continue ;
q.push(make(change(now.num,_0-3,_0),now.where)) ;
mp[make(change(now.num,_0-3,_0),now.where)] = mp[now]+1 ;
}
if ( _0 < 7 ) {
if ( mp[make(change(now.num,_0+3,_0),now.where)] != 0 ) continue ;
q.push(make(change(now.num,_0+3,_0),now.where)) ;
mp[make(change(now.num,_0+3,_0),now.where)] = mp[now]+1 ;
}
if ( _0%3 != 1 ) {
if ( mp[make(change(now.num,_0-1,_0),now.where)] != 0 ) continue ;
q.push(make(change(now.num,_0-1,_0),now.where)) ;
mp[make(change(now.num,_0-1,_0),now.where)] = mp[now]+1 ;
}
if ( _0%3 != 0 ) {
if ( mp[make(change(now.num,_0+1,_0),now.where)] != 0 ) continue ;
q.push(make(change(now.num,_0+1,_0),now.where)) ;
mp[make(change(now.num,_0+1,_0),now.where)] = mp[now]+1 ;
}
}
return 0 ;
}