#include #include using namespace std; int dp[10001][2]; int main(){ string s;cin>>s; reverse(s.begin(),s.end()); for(int i = 0; s.size() > i; i++){ dp[i][0] = -1; dp[i][1] = -1; } for(int j = 0; 10 > j; j++){ if(s[0]-'0' > j){ if(dp[0][1] == -1)dp[0][1] = (j>4?j-4:j)+(10+j-(s[0]-'0')>4?10+j-(s[0]-'0')-4:10+j-(s[0]-'0')); else dp[0][1] = min(dp[0][1],(j>4?j-4:j)+(10+j-(s[0]-'0')>4?10+j-(s[0]-'0')-4:10+j-(s[0]-'0'))); }else{ if(dp[0][0] == -1)dp[0][0] = (j>4?j-4:j)+(j-(s[0]-'0')>4?j-(s[0]-'0')-4:j-(s[0]-'0')); else dp[0][0] = min(dp[0][0],(j>4?j-4:j)+(j-(s[0]-'0')>4?j-(s[0]-'0')-4:j-(s[0]-'0'))); } } for(int i = 1; s.size() > i; i++){ for(int j = 0; 10 > j; j++){ //dp[i-1][1]の処理 if(dp[i-1][1] != -1){ if(s[i]-'0' >= j){ if(dp[i][1] == -1)dp[i][1] = dp[i-1][1]+(j>=5?j-4:j)+(10+j-(s[i]-'0'+1)>4?10+j-(s[i]-'0'+1)-4:10+j-(s[i]-'0'+1)); else dp[i][1] = min(dp[i][1],dp[i-1][1]+(j>=5?j-4:j)+(10+j-(s[i]-'0'+1)>4?10+j-(s[i]-'0'+1)-4:10+j-(s[i]-'0'+1))); }else{ if(dp[i][0] == -1)dp[i][0] = dp[i-1][1]+(j>=5?j-4:j)+(j-(s[i]-'0'+1)>4?j-(s[i]-'0'+1)-4:j-(s[i]-'0'+1)); else dp[i][0] = min(dp[i][0],dp[i-1][1]+(j>=5?j-4:j)+(j-(s[i]-'0'+1)>4?j-(s[i]-'0'+1)-4:j-(s[i]-'0'+1))); } } //dp[i-1][0]の処理 if(dp[i-1][0] != -1){ if(s[i]-'0' > j){ if(dp[i][1] == -1)dp[i][1] = dp[i-1][0]+(j>=5?j-4:j)+(10+j-(s[i]-'0')>4?10+j-(s[i]-'0')-4:10+j-(s[i]-'0')); else dp[i][1] = min(dp[i][1],dp[i-1][0]+(j>=5?j-4:j)+(10+j-(s[i]-'0')>4?10+j-(s[i]-'0')-4:10+j-(s[i]-'0'))); }else{ if(dp[i][0] == -1)dp[i][0] = dp[i-1][0]+(j>=5?j-4:j)+(j-(s[i]-'0')>4?j-(s[i]-'0')-4:j-(s[i]-'0')); else dp[i][0] = min(dp[i][0],dp[i-1][0]+(j>=5?j-4:j)+(j-(s[i]-'0')>4?j-(s[i]-'0')-4:j-(s[i]-'0'))); } } } } cout << min(dp[s.size()-1][0],dp[s.size()-1][1]+1) << endl; }