#include<iostream> #include<string> #include<algorithm> using namespace std; int MinValue(int a,int b,int c) { int min=a; if(b<min) min=b; if(c<min) min=c; return min; } int Distance(string strA,int pABegin,int pAEnd, string strB,int pBBegin,int pBEnd) { if(pABegin>pAEnd) { if(pBBegin>pBEnd) return 0; else return pBEnd-pABegin+1; } if(pBBegin>pBEnd) { if(pABegin>pAEnd) return 0; else return pAEnd-pABegin+1; } if(strA[pABegin]==strB[pBBegin]) return Distance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd); else { int t1=Distance(strA,pABegin+1,pAEnd,strB,pBBegin,pBEnd); int t2=Distance(strA,pABegin,pAEnd,strB,pBBegin+1,pBEnd); int t3=Distance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd); return MinValue(t1,t2,t3)+1; } } int main(int argc,char *argv[]) { string strA,strB; cin>>strA; cin>>strB; int ans=Distance(strA,0,strA.length()-1,strB,0,strB.length()-1); cout<<ans<<endl; }
j | ||||
C(i-1,j-1) | C(i-1,j) | |||
i | C(i,j-1) | C(i,j) | ||
#include<iostream> #include<string> #include<algorithm> #define MAX 1000 using namespace std; int dp[MAX][MAX]; int MinValue(int a,int b,int c) { int min=a; if(b<min) min=b; if(c<min) min=c; return min; } int Distance(string strA,string strB) { int i,j; int lenA=strA.length()+1; int lenB=strB.length()+1; for(i=0;i<lenA;i++) dp[i][0]=i; for(j=0;j<lenB;j++) dp[0][j]=j; dp[0][0]=0; for(i=1;i<lenA;i++) { for(j=1;j<lenB;j++) { if(strA[i-1]==strB[j-1]) dp[i][j]=dp[i-1][j-1]; else dp[i][j]=MinValue(dp[i][j-1],dp[i-1][j],dp[i-1][j-1])+1; } } return dp[lenA-1][lenB-1]; } int main(int argc,char *argv[]) { string strA,strB; cin>>strA; cin>>strB; int ans=Distance(strA,strB); cout<<ans<<endl; }
#include<iostream> #include<string> #include<algorithm> #define MAX 1000 using namespace std; int dis[MAX][MAX]; int MinValue(int a,int b,int c) { int min=a; if(b<min) min=b; if(c<min) min=c; return min; } int Distance(string strA,int pABegin,int pAEnd, string strB,int pBBegin,int pBEnd) { if(dis[pABegin][pBBegin]>=0) return dis[pABegin][pBBegin]; if(pABegin>pAEnd) { if(pBBegin>pBEnd) dis[pABegin][pBBegin]=0; else dis[pABegin][pBBegin]=pBEnd-pABegin+1; return dis[pABegin][pBBegin]; } if(pBBegin>pBEnd) { if(pABegin>pAEnd) dis[pABegin][pBBegin]=0; else dis[pABegin][pBBegin]=pAEnd-pABegin+1; return dis[pABegin][pBBegin]; } if(strA[pABegin]==strB[pBBegin]) { dis[pABegin][pBBegin]=Distance(strA,pABegin+1,pAEnd, strB,pBBegin+1,pBEnd); return dis[pABegin][pBBegin]; } else { int t1=Distance(strA,pABegin+1,pAEnd,strB,pBBegin,pBEnd); int t2=Distance(strA,pABegin,pAEnd,strB,pBBegin+1,pBEnd); int t3=Distance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd); dis[pABegin][pBBegin]=MinValue(t1,t2,t3)+1; return dis[pABegin][pBBegin]; } } int main(int argc,char *argv[]) { int i,j; string strA,strB; cin>>strA; cin>>strB; for(i=0;i<MAX;i++) for(j=0;j<MAX;j++) dis[i][j]=-1; int ans=Distance(strA,0,strA.length()-1,strB,0,strB.length()-1); cout<<ans<<endl; }
原文地址:http://blog.csdn.net/cstopcoder/article/details/26747181