2018湖南多校第二场-20180407 Column Addition

Description

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

Hint

Source

ATRC2017

 

开始是用贪心写的,总感觉自己没错,贪心的判断写了一层又一层最后还是错了。

结束后看了学长的代码,用dp写的,顿时有种恍然大悟的感觉,考试的时候钻进死胡同了。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
#define debug(a) cout << #a << ": " << a << endl
int main() {
    int n;
    while( cin >> n ) {
        if( !n ) {
            break;
        }
        string s1, s2, s3;
        cin >> s1 >> s2 >> s3;
        int a[1010], b[1010], c[1010];
        for( int i = 0; i < n; i ++ ) {
            a[i] = s1[i] - '0';
            b[i] = s2[i] - '0';
            c[i] = s3[i] - '0';
        }
        int dp[1010];
        memset( dp, 0, sizeof(dp) );
        for( int i = n - 1; i >= 0; i -- ) {
            if( ( a[i] + b[i] ) % 10 == c[i] ) { //如果当前直接或者进位后间接满足就置为1
                dp[i] = 1;
            }
            for( int j = i + 1; j < n; j ++ ) {
                int jinwei = ( dp[j] ) && ( a[j] + b[j] > c[j] ); //后面是否有可以进位的
                if( ( a[i] + b[i] + jinwei ) % 10 == c[i] ) {
                    dp[i] = max( dp[i], dp[j] + 1 ); //有的话就更新i位置的dp值
                }
            }
        }
        int ans = n;
        for( int i = 0; i < n; i ++ ) {
            if( a[i] + b[i] <= c[i] ) {
                ans = min( ans, n - dp[i] );
            }
        }
        cout << ans << endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/l609929321/p/8797193.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值