标签:pac gbk form result ued ini alc should and
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,给出三个n位数,你可以同时去掉这三个数中的同一位数,使第一个数加第二个数等于第三个数,问最小需要去掉几位。
这是一个DP题,贪心的去是不对的,随便举个例子即可证明贪心错误。
设\(dp[i]\)为到第i位最多可以保留多少位,用一个变量ans1存储最大能保留多少位。设a[i]为第一串数字的第i个数,b[i]为第二串数字的第i个数,ans[i]为第三串数字的第i个数,从n到1处理加法。
若(a[i]+b[i])%10==ans[i],说明这一位可以保留,将f[i]设为1,如果有进位,将i处进位(k[i])设为1,如果没有进位,k[i] = 0, 更新答案最大值,只在不进位时更新最大值是有原因的,因为如果进位的话,你无法确定这一位是否该留,比如99 99 98,均满足相等,但都有进位,一个也不能留
然后从n到i枚举j,如果(a[i]+b[i]+k[j])%10==1,那么f[i]=max(f[i], f[j] + 1),同样有进位的话更新k[i],无进位时更新一下最大能保留多少位,最后取输出n-ans1即可
#include<bits/stdc++.h>
using namespace std;
int a[1050], b[1050], ans[1050], f[1050];
int k[1050];
int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (n == 0) break;
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", &ans[i]);
}
int ans1 = 0;
memset(f, 0, sizeof(f));
memset(k, 0, sizeof(k));
for (int i = n; i >= 1; i--) {
if ((a[i] + b[i]) % 10 == ans[i]) {
f[i] = 1;
if (a[i] + b[i] - 10 == ans[i]) k[i] = 1;
else {
k[i] = 0;
ans1 = max(ans1, f[i]);
}
}
for (int j = n; j > i; j--) {
if ((a[i] + b[i] + k[j]) % 10 == ans[i]) {
f[i] = max(f[i], f[j] + 1);
if (a[i] + b[i] + k[j] - 10 == ans[i]) k[i] = 1;
else {
k[i] = 0;
ans1 = max(ans1, f[i]);
}
}
}
}
printf("%d\n", n - ans1);
}
return 0;
}
/**********************************************************************
Problem: 2034
User: Artoriax
Language: C++
Result: AC
Time:148 ms
Memory:2044 kb
**********************************************************************/
标签:pac gbk form result ued ini alc should and
原文地址:https://www.cnblogs.com/artoriax/p/10351835.html