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.
IllustrationA 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
题目大意:给你2个字符串,要你求出一个字符串变到另一个字符串的最小次数。
解题思路:用DP。
d[i][j]表示长度为i的字符串变到长度为j的字符串的最小变换次数。
if(s1[i]=s2[j])
d[i][j]=d[i-1][j-1];
否则
d[i][j]=min(d[i-1][j]+1,d[i][j-1]+1,d[i-1][j-1]+1);
代码:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 const int maxn=1000+10; 5 int min(int x,int y) 6 { 7 if(x<y) 8 return x; 9 else return y; 10 } 11 int d[maxn][maxn]; 12 int main() 13 { 14 string a,b; 15 int l1,l2,i,j; 16 while(cin>>l1>>a>>l2>>b) 17 { 18 for(i=0;i<=l1;i++) 19 for(j=0;j<=l2;j++) 20 d[i][j]=0; 21 for(i=1;i<=l1;i++) 22 d[i][0]=i; 23 for(j=1;j<=l2;j++) 24 d[0][j]=j; 25 for(i=1;i<=l1;i++) 26 { 27 for(j=1;j<=l2;j++) 28 { 29 if(a[i-1]==b[j-1]) 30 d[i][j]=d[i-1][j-1]; 31 else 32 { 33 d[i][j]=min(d[i-1][j]+1,d[i][j-1]+1); 34 d[i][j]=min(d[i][j],d[i-1][j-1]+1); 35 } 36 } 37 } 38 cout<<d[l1][l2]<<endl; 39 } 40 return 0; 41 }