链接:点击打开链接
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.
Input
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.
Output
For each test case, print a single line containing the minimum number of columns needed to be erased.
Sample Input
3 123 456 579 5 12127 45618 51825 2 24 32 32 5 12299 12299 25598 0
Sample Output
0 2 2 1
题意:给出一个n,输入三个数组,数组长度是n。要求算出数组去掉几个元素后,能够第一个数组加上第二个数组等于第三个数组。
思路:动态规划,从后往前逐步动规,dp[0][i]表示到i点不进位所去掉的点,dp[1][i]是往高位进位去掉的点。具体看注释
#include <iostream>
#define MAX_N (int) 1e3+10
using namespace std;
int main()
{
int n,dp[2][MAX_N]; //动规数组,dp[0][i]表示到i点不进位所去掉的点,dp[1][i]是进位去掉的点
string s,t,r; //相加的数组和给出的结果数组
ios_base::sync_with_stdio(false);
cin.tie(0);
while(cin>>n){
if(n == 0) break;
cin>>s>>t>>r;
for(int i=0;i<1005;i++)dp[0][i] = dp[1][i] =MAX_N; //相当于最先设置全部删除
dp[0][n]=0;
for(int i=n-1;i>=0;--i){ //从后往前
int 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==z-1){ //需要低位进位才正确
dp[0][i]=min(dp[0][i],dp[1][i+1]);
}
else if(x+y-10==z){ //不需要低位进位就能进位
dp[1][i]=min(dp[1][i],dp[0][i+1]);
}
else if(x+y-10==z-1){ //需要低位进位才能进位
dp[1][i]=min(dp[1][i],dp[1][i+1]);
}
}
cout<<dp[0][0]<<endl; //输出到最左边没有继续进位的
}
return 0;
}