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


    问题描述

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

    编程任务

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

    样例

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

    fxpimu

    -xwrs-

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

     

    源程序代码如下:

    源程序代码
     1 #include <string>
     2 #include <iostream>  
     3 #include <fstream>
     4 using namespace std;
     5 
     6 ifstream fin("f:\\input.txt");
     7 ofstream fout("f:\\output.txt");
     8 
     9 string s1,s2;
    10 
    11 
    12 int min(int a, int b, int c)
    13 {
    14     int temp=(a<b)?a:b;
    15     return (temp<c)?temp:c;
    16 }
    17 
    18 
    19 void distance(int lens1, int lens2)  
    20 {
    21     int m;
    22     int **d = new int *[lens1+1];
    23     for(m=0;m<=lens1;m++)
    24         d[m] = new int[lens2+1];
    25 
    26 
    27 
    28 
    29     for(int i=0; i<=lens1; i++)
    30         d[i][0]=i;  
    31     for(int j=0; j<=lens2; j++)
    32         d[0][j]=j;
    33     for(int i=1; i<=lens1; i++)
    34     {
    35         for(int j=1; j<=lens2; j++)
    36         {
    37             int cost=(s1[i-1]==s2[j-1]) ? 0 : 1; 
    38             int deletion=d[i-1][j]+1;
    39             int insertion=d[i][j-1]+1;
    40             int substitution=d[i-1][j-1]+cost;
    41             d[i][j]=min(deletion, insertion, substitution);
    42         }
    43     }
    44     for(int i=0; i<=lens1; i++)
    45     {
    46         for(int j=0; j<=lens2; j++) 
    47         {
    48             fout<<d[i][j];
    49         }
    50         fout<<endl;
    51     }
    52     fout<<d[lens1][lens2]<<endl;
    53 }
    54 
    55 int main()
    56 {
    57     fin>>s1;
    58     fin>>s2;
    59 
    60     distance(s1.size(),s2.size());
    61 
    62     return 1;
    63 
    64 }
  • 相关阅读:
    按日期重命名宾得相机的照片
    Intellij笔记
    quartznet笔记
    优秀的UI插件
    我的ORM之示例项目
    Redis笔记
    Idol之坑
    ORACLE查询表最近更改的数据 VERSIONS BETWEEN TIMESTAMP MINVALUE AND MAXVALUE
    如何drop大表的中不用的字段 set unused column
    Oracle DUL/AUL/ODU 工具说明
  • 原文地址:https://www.cnblogs.com/shaoweinan/p/2798668.html
Copyright © 2020-2023  润新知