#include<iostream> #include<string> using namespace std; /* 计算A[1,...,lenA]和B[1,...,lenB]的相似度可以采用动态规划计算A[2,...,lenA]和B[1,...,lenB]的相似度, A[1,...,lenA]和B[2,...,lenB]的相似度,A[2,...,lenA]和B[2,...,lenB]的相似度,然后取这三个相似度值最大的即为 A[1,...,lenA]和B[1,...,lenB]的相似度。 */ int minValue(int t1,int t2,int t3) { int temp=(t1<t2)?t1:t2; temp=(t3<temp)?t3:temp; return temp; } int CalculateStringDistance(string strA,int pABegin,int pAEnd,string strB,int pBBegin,int pBEnd) { if(pABegin>pAEnd) { if(pBBegin>pBEnd)return 0; else return pBEnd-pBBegin+1; } if(pBBegin>pBEnd) { if(pABegin>pAEnd)return 0; else return pAEnd-pABegin+1; } if(strA[pABegin]==strB[pBBegin]) { return CalculateStringDistance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd); } else { int t1=CalculateStringDistance(strA,pABegin+1,pAEnd,strB,pBBegin,pBEnd); int t2=CalculateStringDistance(strA,pABegin,pAEnd,strB,pBBegin+1,pBEnd);; int t3=CalculateStringDistance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd); return minValue(t1,t2,t3)+1; } } int main() { string strA,strB; while(true) { cin>>strA>>strB; int lenA=strA.length(); int lenB=strB.length(); double similar=CalculateStringDistance(strA,0,lenA-1,strB,0,lenB-1); similar=1/(similar+1); cout<<similar<<endl; } system("pause"); return 0; }