保险箱
每一位由低位推出的,每一位可能进位,退位,不进不退三种状态
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
int n;
const int N = 1e5 + 10;
int a[N],b[N];
int dp[N][3];
//0表示不进位不退位
//1表示进位
//2表示退位
int op1(int a,int b){
return abs(a-b);
//不进不退
}
int op2(int a,int b){
return abs(10-a+b);
//进位4 2 --> 4 -> 10 ->2
}
int op3(int a,int b){
return abs(a+10-b);
//退位4 2 --> 4 -> 0(10) -> 2
}
void solve(){
string x,y;
cin >> n >> x >> y;
reverse(x.begin(),x.end()),reverse(y.begin(),y.end());
x = " " + x , y = " " + y;
for(int i = 1 ; i <= n ; i ++){
a[i] = x[i] - '0';
b[i] = y[i] - '0';
}
for(int i = 1 ; i <= n ; i ++) dp[i][0] = dp[i][1] = dp[i][2] = 0x3f3f3f3f;
dp[1][0] = op1(a[1],b[1]);
dp[1][1] = op2(a[1],b[1]);
dp[1][2] = op3(a[1],b[1]);
for(int i = 2 ; i <= n ; i ++){
dp[i][0] = min({dp[i-1][0]+op1(a[i],b[i]),dp[i-1][1]+op1(a[i]+1,b[i]),dp[i-1][2]+op1(a[i]-1,b[i])});
dp[i][1] = min({dp[i-1][0]+op2(a[i],b[i]),dp[i-1][1]+op2(a[i]+1,b[i]),dp[i-1][2]+op2(a[i]-1,b[i])});
dp[i][2] = min({dp[i-1][0]+op3(a[i],b[i]),dp[i-1][1]+op3(a[i]+1,b[i]),dp[i-1][2]+op3(a[i]-1,b[i])});
}
cout << min({dp[n][0],dp[n][1],dp[n][2]});
}
signed main(){
ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int _ = 1;
//cin >> _;
while(_--) solve();
return 0;
}
var code = "7d936adf-0bcb-4b34-bb45-e089bca65d74"