#include "iostream"
#include "algorithm"
#include "fstream"
using namespace std;
/*
d[i,j] = 0 a[i] = b[j]
= 1 a[i] != b[j]
D[i,j] = min{D[i-1][j-1]+d[i][j], D[i-1][j]+1, D[i][j-1]+1}
D[i][0] = i
D[0][j] = j
解释:
将a[i]改为b[j]需要d[i][j]次操作 D[i-1][j-1]+d[i][j]
a中删除a[i],需要1次操作 D[i-1][j]+1
a中插入b[j],需要1次操作 D[i][j-1]+1
*/
int D[100][100];
int min(int a, int b, int c)
{
int temp = a<b? a:b;
return temp<c? temp:c;
}
int change(char a[], char b[])
{
int lena = strlen(a)-1;
int lenb = strlen(b)-1;
for(int i=0; i<=lena; i++)
D[i][0] = i;
for(int j=0; j<=lenb; j++)
D[0][j] = j;
for(i=1; i<=lena; i++)
for(j=1; j<=lenb; j++)
D[i][j] = min(D[i-1][j-1]+ !(a[i]==b[j]), D[i-1][j]+1, D[i][j-1]+1);
return D[lena][lenb];
}
int main()
{
ifstream fin("string.txt");
char a[100];
char b[100];
cout << "输入字符串a:";
fin >> a+1; cout << a+1;
cout << "\n输入字符串b:";
fin >> b+1; cout << b+1;
cout << "\n编辑距离为:" << change(a, b) << endl;
fin.close();
return 0;
}
06-03