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;
}

 

posted on 2018-04-11 17:41  九月旧约  阅读(142)  评论(0编辑  收藏  举报

导航