A multi-digit column addition is a formula on adding two integers written like this:
A multi-digit column addition is written on the blackboard, but the sum is not necessarily correct. We can erase any
number of the columns so that the addition becomes correct. For example, in the following addition, we can obtain a
correct addition by erasing the second and the forth columns.
Your task is to find the minimum number of columns needed to be erased such that the remaining formula becomes a
correct addition.
![](http://exam.upc.edu.cn/upload/image/20180119/20180119160853_82068.jpg)
![](http://exam.upc.edu.cn/upload/image/20180119/20180119160903_49478.jpg)
输入
There are multiple test cases in the input. Each test case starts with a line containing the single integer n, the number of
digit columns in the addition (1 ⩽ n ⩽ 1000). Each of the next 3 lines contain a string of n digits. The number on the third
line is presenting the (not necessarily correct) sum of the numbers in the first and the second line. The input terminates
with a line containing “0” which should not be processed.
输出
For each test case, print a single line containing the minimum number of columns needed to be erased.
题意
模拟计算器,给n位数的加法,给出两加数和结果,但结果中有些列的答案是错误滴,问你至少需要去掉多少列(两加数的结果的列同时去电)之后才能使加法得出的结果正确。
思路:
这道提示一个简单的dp题 从最后一位向前加,从DP[n-1]推到DP[0],这个DP是个二维数组,DP[i][0]表示在i位时不产生进位的情况下最多有多少列成立,DP[i][1]表示在i位时产生进位的情况下最多有多少列成立。因为第一位不能再产生进位了,所以最后最多有DP[0][0]列成立。然后输出DP[0][0]即可。
#include<cstdio>
#include<cstring>
#include<math.h>
#include<algorithm>
#include<queue>
#include<vector>
#include<iostream>
#include<map>
#define mes(a,b) memset(a,b,sizeof(a))
#define rep(i,m,n) for(i=m;i<=n;i++)
#define rap(i,m,n) for(i=m;i>=n;i--)
typedef long long ll;
using namespace std;
int max3(int a,int b,int c){return max(max(a,b),c);}
ll min3(ll a,ll b,ll c){return min(min(a,b),c);}
const double PI=acos(-1);
const int inf=0x3f3f3f3f;
const double esp=1e-6;
const int maxn=1e6+5;
const int mod=1e9+7;
int dir[4][2]={0,1,1,0,0,-1,-1,0};
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll inv(ll b){if(b==1)return 1; return (mod-mod/b)*inv(mod%b)%mod;}
ll fpow(ll n,ll k){ll r=1;for(;k;k>>=1){if(k&1)r=r*n%mod;n=n*n%mod;}return r;}
ll Fpow(ll n,ll k){ll r=1;for(;k;k>>=1){if(k&1)r=r*n;n=n*n;}return r;}
ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}return f;}
int main()
{
char s[10010],t[10010],r[10010];
int dp[10][100010];
int n;
int x,y,z;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
scanf("%s %s %s",s,t,r);
for(int i=0;i<1005;i++)
dp[0][i]=dp[1][i]=inf;
dp[0][n]=0;
for(int i=n-1;i>=0;i--)
{
x=s[i]-'0';
y=t[i]-'0';
z=r[i]-'0';
dp[0][i]=dp[0][i+1]+1;
dp[1][i]=dp[1][i+1]+1;
if(x+y==z)
dp[0][i]=min(dp[0][i],dp[0][i+1]);
else if(x+y-10==z)
dp[1][i]=min(dp[1][i],dp[0][i+1]);
else if(x+y+1==z)
dp[0][i]=min(dp[0][i],dp[1][i+1]);
else if(x+y-9==z)
dp[1][i]=min(dp[1][i],dp[1][i+1]);
}
printf("%d\n",dp[0][0]);
}
return 0;
}