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

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

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.
输入
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;
}

转载于:https://www.cnblogs.com/NeilThang/p/9356617.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值