Description
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 CDeletion: * 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
Source
题意:
给出两个字符串x 与 y,其中x的长度为n,y的长度为m,并且m>=n.然后y可以经过删除一个字母,添加一个字母,转换一个字母,三种操作得到x.问最少可以经过多少次操作
分析:
我们令dp[i][j]==x表示源串的前i个字符变成目串的前j个字符需要x步操作.
初始化: dp[0][i]==i且 dp[i][0]=i.
上述前者表示添加源串i个字符, 后者表示删除源串i个字符.
状态转移: dp[i][j]如果我们只在源串的末尾进行3种操作,那么有下面3种情况.
1. dp[i-1][j-1]+(x[i]==y[j]?0:1).即如果源串和目串最后一个字符相同, 自然dp[i-1][j-1]就是所求. 如果他们最后一个字符不同, 那么可以替换源串的最后一个字符成目串的那个字符.
2. dp[i-1][j]+1.我们可以删除源串最后一个字符(1步删除操作), 然后将源串变成目串(dp[i-1][j]步操作).
3. dp[i][j-1]+1.我们可以将源串变成目串的前j-1个字符的串(dp[i][j-1]步操作),然后在源串末尾再添加一个y[j]即变成了目串(1步操作).
最终所求: 上述三个式子的最小值.
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1000+5;
int n,m;
int dp[maxn][maxn];
char s1[maxn],s2[maxn];
int main()
{
while(scanf("%d%s",&n,s1)==2)
{
scanf("%d%s",&m,s2);
for(int i=0;i<=m;i++)
dp[0][i]=i;
for(int i=0;i<=n;i++)
dp[i][0]=i;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
dp[i][j]=dp[i-1][j-1]+(s1[i-1]==s2[j-1]?0:1);
dp[i][j]=min(dp[i][j], min(dp[i-1][j]+1,dp[i][j-1]+1));
}
printf("%d\n",dp[n][m]);
}
return 0;
}