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.
有大佬说这是一道最长上升子序列的变形。想了好久终于有了一点感觉,这道dp说实话还挺简单的,不过我太菜,做不出来就是了,此处立个flag,好好学dp!!!!!
下面直接上代码。附有详细注释
#include <iostream>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <stdio.h>
#define LL long long
using namespace std;
const LL MAX = 1005;
int main(int argc, char const *argv[]){
while(1){
int n;
int a[MAX] = {0};
int b[MAX] = {0};
int c[MAX] = {0};
int dp[MAX][2]; // dp[i][0]表示第i为不进1所能得到的最大正确的位数,dp[i][1]进1所能得到的最大正确的位数, 因为第一位不能进一,所以结果为 n - dp[0][0]
scanf("%d", &n);
if(n == 0){
break;
}
for(int i = 0; i <= n; i++){ // 注意,由于是多组输入,一定要将第n为也初始化
for(int j = 0; j < 2; j++){
dp[i][j] = 0;
}
}
for(int i = 0; i < n; i++){
scanf("%1d", &a[i]);
}
for(int i = 0; i < n; i++){
scanf("%1d", &b[i]);
}
for(int i = 0; i < n; i++){
scanf("%1d", &c[i]);
}
for(int i = n - 1; i >= 0; i--){
if((a[i] + b[i]) % 10 == c[i]){
if(a[i] + b[i] > 9){ // 如果大于9,则需要进1,该为才是正确的
dp[i][1] = dp[i + 1][0] + 1; //因为是(a[i] + b[i]) % 10 == c[i],所以要使该位正确,上一位不能进1.
} else{
dp[i][0] = dp[i + 1][0] + 1;
}
}
if(dp[i + 1][1]){// 如过之前存在进位,则考虑(a[i] + b[i] + 1) % 10 == c[i]的情况,此处不必考虑该为在输入中的上一位有没有进1,原因在于第60行代码
if((a[i] + b[i] + 1) % 10 == c[i]){
if(a[i] + b[i] + 1 > 9){
dp[i][1] = dp[i + 1][1] + 1;//因为是(a[i] + b[i] + 1) % 10 == c[i],所以要使该位正确,上一位必须进1
} else{
dp[i][0] = dp[i + 1][1] + 1;
}
}
}
dp[i][0] = max(dp[i][0], dp[i + 1][0]); // 这里可能就是和求最长上升子序列的相似的地方,将该为更新为两种情况下的最大数量
dp[i][1] = max(dp[i][1], dp[i + 1][1]);
}
printf("%d\n", n - dp[0][0]);
}
return 0;
}