一、内容
Let x and y be two strings over some finite alphabet A. We would like to transform x into y allowing only operations given below:
Deletion: a letter in x is missing in y at a corresponding position.
Insertion: a letter in y is missing in x at a corresponding position.
Change: letters at corresponding positions are distinct
Certainly, we would like to minimize the number of all possible operations.
Illustration
A G T A A G T * A G G C
| | | | | | |
A G T * C * T G A C G C
Deletion: * in the bottom line
Insertion: * in the top line
Change: when the letters at the top and bottom are distinct
This tells us that to transform x = AGTCTGACGC into y = AGTAAGTAGGC we would be required to perform 5 operations (2 changes, 2 deletions and 1 insertion). If we want to minimize the number operations, we should do it like
A G T A A G T A G G C
| | | | | | |
A G T C T G * A C G C
and 4 moves would be required (3 changes and 1 deletion).
In this problem we would always consider strings x and y to be fixed, such that the number of letters in x is m and the number of letters in y is n where n ≥ m.
Assign 1 as the cost of an operation performed. Otherwise, assign 0 if there is no operation performed.
Write a program that would minimize the number of possible operations to transform any string x into a string y.
Input
The input consists of the strings x and y prefixed by their respective lengths, which are within 1000.
Output
An integer representing the minimum number of possible operations to transform any string x into a string y.
Sample Input
10 AGTCTGACGC
11 AGTAAGTAGGC
Sample Output
4
二、思路
- dp【i】【j】: 代表字符串a用到了i个字符,字符串b用到了j个字符,使2个字符串相等最少用的操作数。
- 由3个状态转移而来:
(1)修改第j个字符使得和第i字符相等 dp[i - 1][j - 1] + 1
(2)删除第j个字符, dp【i】【j - 1】 + 1
(3)增加一个字符和i相等.dp【i - 1】【j】 + 1
三、代码
#include <cstdio>
#include <cstring>
#define min(a, b) (a > b ? b : a)
using namespace std;
const int N = 1005;
int n, m, dp[N][N];
char a[N], b[N];
int main() {
while (scanf("%d%s%d%s", &n, a + 1, &m, b + 1) != EOF) {
memset(dp, 0, sizeof(dp));
//初始化
for (int i = 1; i <= n; i++) dp[i][0] = i;
for (int i = 1; i <= m; i++) dp[0][i] = i;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = dp[i - 1][j - 1];
if (a[i] != b[j]) dp[i][j] += 1;
dp[i][j] = min(dp[i][j], dp[i][j - 1] + 1);
dp[i][j] = min(dp[i][j], dp[i - 1][j ] + 1);
}
}
printf("%d\n", dp[n][m]);
}
return 0;
}