A - String Distance and Transform Process solution
InputInput consists a sequence of string pairs, each string pair consists two lines, each string occupies one line. The length of each string will be no more than 80.
OutputFor each string pair, you should give an integer to indicate the distance between them at the first line, and give a sequence of command to transform string 1 to string 2. Each command is a line lead by command count, then the command. A command must be
Insert pos,value
Delete pos
Replace pos,value
where pos is the position of the string and pos should be between 1 and the current length of the string (in Insert command, pos can be 1 greater than the length), and value is a character. Actually many command lists can satisfy the request, but only one of them is required.
Sample Input
abcac bcd aaa aabaaaa
Sample Output
3 1 Delete 1 2 Replace 3,d 3 Delete 4 4 1 Insert 1,a 2 Insert 2,a 3 Insert 3,b 4 Insert 7,a
题意:有两个字符串,可以对第一个字符串进行三种操作:1.删除一个字符 2.插入一个字符 3.替换一个字符 将第一个字符串变成第二个字符串,求最少做几次操作
//#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 85; char A[maxn],B[maxn]; int dp[maxn][maxn],len1,len2; void path() { int i,j,step; int index=1; i=len1; j=len2; step=dp[len1][len2]; while(i>0 || j>0) {//处理边界 if(i>0 && j==0) { printf("%d Delete %d\n",index++,i); //cout<<index++<<" "<<"Delete"<<" "<<i<<endl; i--; continue; } else if(i==0 && j>0) { printf("%d Insert 1,%c\n",index++,B[j-1]); //cout<<index++<<" "<<"Insert"<<" "<<1<<","<<B[j-1]<<endl; j--; continue; } else { //三种状态 if(step == dp[i-1][j-1] && A[i-1] == B[j-1]) { i--; j--; }//更改一个元素 else if(step == dp[i-1][j-1]+1) { printf("%d Replace %d,%c\n",index++,i,B[j-1]); //cout<<index++<<" "<<"Replace"<<" "<<i<<","<<B[j-1]<<endl; step--; i--; j--; } //添加一个元素 else if(step == dp[i][j-1]+1) { printf("%d Insert %d,%c\n",index++,i+1,B[j-1]); //cout<<index++<<" "<<"Insert"<<" "<<i+1<<","<<B[j-1]<<endl; step--; j--; } //删除一个元素 else if( step == dp[i-1][j]+1) { printf("%d Delete %d\n",index++,i); //cout<<index++<<" "<<"Delete"<<" "<<i<<endl; step--; i--; } } } } int main() { while(scanf("%s %s",A,B)!=EOF) { getchar(); len1 = strlen(A); len2 = strlen(B); memset(dp,0,sizeof(dp)); for(int i = 0; i <= len1; i++)//初始化空序列 dp[i][0] = i; for(int i = 0; i <= len2; i++) dp[0][i] = i; for(int i = 1; i <= len1; i++) { for(int j = 1; j <= len2; j++) { int tmp = min(dp[i][j-1],dp[i-1][j]) + 1; int d = A[i-1] == B[j-1] ? 0 : 1; dp[i][j] = min(tmp,dp[i-1][j-1]+d); } } printf("%d\n",dp[len1][len2]); //cout<<dp[len1][len2]<<endl; path(); } return 0; }
通过测试,注释量和cin,cout都会消耗一定的时间