POJ3356-AGTC-dp+字符串处理
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
题意:
每组数据给出两个字符串x、y,通过删除或添加或替换三种操作把两个字符串变得相同。
求最少操作次数。
思路:
可以先定义一个dp[n+20][m+20]的二维数组,要明白题目求的是什么,根据需要去写题,而且要时刻记住题目求的是什么,自己定义的东西的具体含义到底是什么。
dp[i][j]代表,从长度为i的a数组到长度为j的b数组最少变换次数。
经过分析,可以得出来一个思想——同化思想,删除和添加可以看作是一种操作,比如a串可以通过添加'c'这个字符变得和b串一样,那也就说明b数组可以通过删除操作,删除'c'变得和a
串一样,所以可以说明通过添加操作和删除操作所需操作次数是确定的,
所以题目可以转换成,通过添加或者替换操作,最少把a、b串变的相同需要多少步。
注意:
a[i]!=b[i],是逻辑表达式,只有两个返回值,满足条件返回值为1,不满足返回为0;
if(1-1),是属于算数表达式,注意区分。
碰到题目一定要去好好思考,好好思考,好好思考。
1 #include<string.h> 2 #include<stdio.h> 3 #include<algorithm> 4 using namespace std; 5 const int N=1020; 6 7 char a[N],b[N]; 8 int dp[N][N]; 9 10 int main() 11 { 12 int n,m; 13 while(~scanf("%d%s%d%s",&n,a,&m,b)) 14 { 15 memset(dp,0,sizeof(dp)); 16 for(int i=0;i<=n;i++) 17 dp[i][0]=i; 18 for(int i=0;i<=m;i++) 19 dp[0][i]=i; 20 for(int i=1;i<=n;i++) 21 { 22 for(int j=1;j<=m;j++) 23 { 24 dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1); 25 dp[i][j]=min(dp[i][j],dp[i-1][j-1]+(a[i-1]!=b[j-1])); 26 } 27 } 28 printf("%d\n",dp[n][m]); 29 30 } 31 return 0; 32 }