【动态规划】Column Addition @ICPC2017Tehran/upcexam5434

时间限制: 1 Sec 内存限制: 128 MB
题目描述

A multi-digit column addition is a formula on adding two integers written like this:
【动态规划】Column Addition @ICPC2017Tehran/upcexam5434
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.
【动态规划】Column Addition @ICPC2017Tehran/upcexam5434
Your task is to find the minimum number of columns needed to be erased such that the remaining formula becomes a correct addition.
输入
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.
样例输入
3
123
456
579
5
12127
45618
51825
2
24
32
32
5
12299
12299
25598
0
样例输出
0
2
2
1

给你一个只有两个数相加的,长度为n列的加法竖式,问最少删去几列使得竖式成立。
设两个相加的数为a和b,和为c
如果要使第i列的等式成立,应该满足下面四种情况的一种:
1. a[i]+b[i] == c[i]; 刚好
2. a[i]+b[i]-10 == c[i]; 产生进位
3. a[i]+b[i]+1 == c[i]; 接受进位后成立
4. a[i]+b[i]+1-10 == c[i]; 接受进位成立且产生进位
我是从左往右推,令dp[i][0] (i from 1)表示第i位不接受进位时,最少删去的列数;
令dp[i][1] 表示第i位接受进位时,最少删去的列数;
因为第n位一定不接受进位,所以输出dp[n][0]表示答案;
转移方程详见代码
读者也可尝试从右往左推

#define IN_LB() freopen("F:\\in.txt","r",stdin)
#define IN_PC() freopen("C:\\Users\\hz\\Desktop\\in.txt","r",stdin)
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
const int INF = 0x3f3f3f3f;
int a[maxn],b[maxn],c[maxn],dp[maxn][2];
int main() {
// IN_LB();
int n;
while(scanf("%d",&n)&&n) {
for(int i=1; i<=n; i++)scanf("%1d",a+i);
for(int i=1; i<=n; i++)scanf("%1d",b+i);
for(int i=1; i<=n; i++)scanf("%1d",c+i);
dp[0][1] = INF;
for(int i=1; i<=n; i++) {
if(a[i]+b[i]==c[i]) {
dp[i][0] = dp[i-1][0];
} else if(a[i]+b[i]-10==c[i]) {
dp[i][0] = min(dp[i-1][0]+1,dp[i-1][1]);
} else dp[i][0] = dp[i-1][0]+1;
if(a[i]+b[i]+1 ==c[i]) {
dp[i][1] = min(dp[i-1][1]+1,dp[i-1][0]);
} else if(a[i]+b[i]+1-10==c[i]) {
dp[i][1] = dp[i-1][1];
} else dp[i][1] = dp[i-1][1]+1;
}
printf("%d\n",dp[n][0]);
}
return 0;
}
上一篇:WKWebView 里 JS 和 native 通信的例子


下一篇:display:inline-block; 在css中是什么意思?