//题意:给你两个字符串,叫你求出最少操作次数,使两个字符串相同;
//思路:找出字符串中最长公共子串,用max(Len1,Len2)-dp[Len1][Len2]求最长公共子串:if(a[i-1]==a[j-1],dp[i][j]=dp[i-1][j-1]+1;else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
AC代码:
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; #define N 1051 char a[N]; char b[N]; short int dp[N][N]; int main() { int m,n; while(scanf("%d%s%d%s",&m,a,&n,b)!=EOF) { int i,j; for(i=0; i<=m; i++) { dp[i][m]=0; } for(i=0; i<=n; i++) { dp[n][i]=0; } for(i=1; i<=m; i++) { for(j=1; j<=n; j++) { if(a[i-1]==b[j-1]) { dp[i][j]=dp[i-1][j-1]+1; } else { dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } printf("%d\n",max(m,n)-dp[m][n]); } }