〖編程·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。
源程序代码如下:
源程序代码
设 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; }
相关文章推荐
- 王晓东 编辑距离问题
- codevs 2598 编辑距离问题
- 字符串编辑距离问题
- 51nod动态规划入门--编辑距离问题
- 哈理工OJ 1284 编辑距离(DP问题)
- 动态规划问题学习路线:斐波那契数列,最大递增子序列,松鼠捡苹果,最大公共子序列,字符串编辑距离
- Codevs 2598 编辑距离问题 dp
- 51nod编辑距离问题
- 字符串编辑距离问题
- NOJ 1224 编辑距离问题 (线性dp 分类)
- 编辑距离问题
- 编辑距离问题算法分析
- 编辑距离问题 【DP 初步】
- 51nod 编辑距离问题 dp
- codevs 2598 编辑距离问题
- 编辑距离问题
- java--动态规划--编辑距离问题
- 编辑距离问题
- 编辑距离问题c语言实现
- 最优编辑距离问题