您的位置:首页 > 编程语言 > C语言/C++

〖編程·C++〗动态规划算法 - 编辑距离问题

2012-12-02 21:14 239 查看
问题描述

设 A 和 B 是2 个字符串。要用最少的字符操作将字符串A 转换为字符串B。这里所说的字符操作包括:(1)删除一个字符;(2)插入一个字符;(3)将一个字符改为另一个字符。将字符串 A 变换为字符串 B 所用的最少字符操作数称为字符串A到B 的编辑距离,记为d(A, B) 。试设计一个有效算法,对任给的2 个字符串A和B,计算出它们的编辑距离d(A,B)。

编程任务

对于给定的字符串A和字符串B,编程计算其编辑距离d(A,B)。

样例

例如,字符串fxpimu和字符串xwrs的对齐方式为

fxpimu

-xwrs-

因此,二者的编辑距离为5。

源程序代码如下:

源程序代码

#include <string>
#include <iostream>
#include <fstream>
using namespace std;

ifstream fin("f:\\input.txt");
ofstream fout("f:\\output.txt");

string s1,s2;

int min(int a, int b, int c)
{
int temp=(a<b)?a:b;
return (temp<c)?temp:c;
}

void distance(int lens1, int lens2)
{
int m;
int **d = new int *[lens1+1];
for(m=0;m<=lens1;m++)
d[m] = new int[lens2+1];

for(int i=0; i<=lens1; i++)
d[i][0]=i;
for(int j=0; j<=lens2; j++)
d[0][j]=j;
for(int i=1; i<=lens1; i++)
{
for(int j=1; j<=lens2; j++)
{
int cost=(s1[i-1]==s2[j-1]) ? 0 : 1;
int deletion=d[i-1][j]+1;
int insertion=d[i][j-1]+1;
int substitution=d[i-1][j-1]+cost;
d[i][j]=min(deletion, insertion, substitution);
}
}
for(int i=0; i<=lens1; i++)
{
for(int j=0; j<=lens2; j++)
{
fout<<d[i][j];
}
fout<<endl;
}
fout<<d[lens1][lens2]<<endl;
}

int main()
{
fin>>s1;
fin>>s2;

distance(s1.size(),s2.size());

return 1;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: