#include < iostream
>
#include
<fstream>
#include
<string>
using
namespace
std;
//readfile
int
readfile(string filename, string & str1,string &str2)
{
ifstream ifile(filename.c_str(),ios_base::in); //
ios_base::binary使用该方式读取时会将\r\n分别读取,导致错误
if (!ifile)
{
cerr
<<
"cannot
open file!\n";
exit(1);
}
getline(ifile,str1);
getline(ifile, str2);
return
0;
}
//将数据写入output文件
template
<typename
T>
inline
int
writefile(string filename, T n)
{
ofstream ofile(filename.c_str(), ios_base::binary | ios_base::out);
if (!ofile)
{
cerr
<<
"cannot
open file!\n";
exit(1);
}
ofile <<
n;
cout <<
"write
over." <<
endl;
return
0;
}
inline
int
get_min(int
x, int
y,int
z)
{
int
temp=(x > y ? y : x);
return
temp > z ? z : temp;
}
int
show_2Dmatrix(int
**ma, int
row, int
col)
{
for
(int
i = 0; i < row; ++i){
for
(int
j = 0; j < col; ++j){
std::cout
<<
"\t"
<<
ma[i][j];
}
std::cout <<
std::endl;
}
return
0;
}
int
editdist(string str1, string str2)
{
int
Len1 =str1.size();
int
Len2 = str2.size();
//申请栈
int
** dist = new int*[Len1+1];
int
** oper = new int*[Len1
+ 1];
for
(int
i = 0; i <= Len1; ++i){
dist[i] = new int[Len2
+ 1];
oper[i] = new int[Len2
+ 1];
}
//初始化
for
(int
col = 0; col <= Len2; ++col){
dist[0][col] = col;//只需增加
oper[0][col] = 2;
}
for
(int
row = 0; row <= Len1; ++row){
dist[row][0] = row;//只需删除
oper[row][0] = 3;
}
oper[0][0] = 0;
//递归
for
(int
i = 1; i <= Len1; ++i){
for
(int
j = 1; j <= Len2; ++j){
int
cost = str1[i - 1] == str2[j - 1] ? 0 : 1;
int
deletion = dist[i - 1][j] + 1;
int
insertion = dist[i][j-1] + 1;
int
substitution = dist[i - 1][j - 1] + cost;
//dist[i][j]
= get_min(deletion, insertion, substitution);
if
(deletion > insertion){
if (substitution > insertion){
dist[i][j] = insertion;
oper[i][j] = 2;
}
else{
dist[i][j] = substitution;
oper[i][j] = cost;
}
}
else{
if (substitution > deletion){
dist[i][j] = deletion;
oper[i][j] = 3;
}
else{
dist[i][j] = substitution;
oper[i][j] = cost;
}
}
}
}
show_2Dmatrix(dist,Len1+1,Len2+1);
cout <<
endl;
show_2Dmatrix(oper, Len1 + 1, Len2 + 1);
int
ans = dist[Len1][Len2];
//释放栈
for
(int
i = 0; i <= Len1; ++i){
delete[]
dist[i];
}
delete[]
dist;
return
ans;
}
int
main()
{
string input, output;
//cin >>
input >> output;
input = "input.txt";
output = "output.txt";
string str1, str2;
readfile(input, str1, str2);
int
ans=editdist(str1, str2);
writefile(output,ans);
system("pause");
return
0;
}