算法导论-15-3-编辑距离
2016-06-13 00:00
411 查看
题目:
![](http://static.oschina.net/uploads/img/201606/13132442_AD5e.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_C1g2.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_8MVf.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_LN2H.gif)
思考:
(1)初始化:
s[0,0]=0
s[i,0] = i * cost(delete)
s[0,j] = j * cost[insert]
(2)递推
![](http://static.oschina.net/uploads/img/201606/13132446_n49L.gif)
(3)最后的操作kill
c[i][j] = MIN(c[m,n], MIN(c[i,n]+cost(kill))), 其中0<=i<m
代码:
![](http://static.oschina.net/uploads/img/201606/13132442_AD5e.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_C1g2.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_8MVf.gif)
![](http://static.oschina.net/uploads/img/201606/13132443_LN2H.gif)
思考:
(1)初始化:
s[0,0]=0
s[i,0] = i * cost(delete)
s[0,j] = j * cost[insert]
(2)递推
![](http://static.oschina.net/uploads/img/201606/13132446_n49L.gif)
(3)最后的操作kill
c[i][j] = MIN(c[m,n], MIN(c[i,n]+cost(kill))), 其中0<=i<m
代码:
#include <iostream> using namespace std; //6种操作的代价,依次是copy,replace,delete,insert,twiddle,kill int cost[6] = {1,1,1,1,1,1}; int s[15][15] = {0}; //字符从0开始计数,s[][]从1开始 int DP(char *x, char *z, int lx, int lz) { int i = 0, j = 0,temp; //初始化s[0][0]=0 //s[i,0] = i * cost(delete) for(i = 1; i <= lx; i++) s[i][0] = i * cost[2]; //s[0,j] = j * cost[insert] for(j = 1; j <= lz; j++) s[0][j] = i * cost[3]; //DP for(i = 0; i < lx; i++) { for(j = 0; j < lz; j++) { s[i+1][j+1] = 0x7fffffff; //copy if(x[i] == z[j]) { temp = s[i][j] + cost[0]; if(temp < s[i+1][j+1]) s[i+1][j+1] = temp; } //replace if(x[i] != z[j]) { temp = s[i][j] + cost[1]; if(temp < s[i+1][j+1]) s[i+1][j+1] = temp; } //delete temp = s[i][j+1] + cost[2]; if(temp < s[i+1][j+1]) s[i+1][j+1] = temp; //insert temp = s[i+1][j] + cost[3]; if(temp < s[i+1][j+1]) s[i+1][j+1] = temp; //twidle if(i && j && x[i] == z[j-1] && x[i-1] == z[j]) { temp = s[i-1][j-1] + cost[4]; if(temp < s[i+1][j+1]) s[i+1][j+1] = temp; } } } //kill int ret = s[lx][lz]; for(i = 1; i < lx; i++) if(s[i][lz] + cost[5] < ret) ret = s[i][lz] + cost[5]; return ret; } void Print(int lx, int lz) { int i, j; for(i = 1; i <= lx; i++) { for(j = 1; j <= lz; j++) cout<<s[i][j]<<' '; cout<<endl; } } int main() { char a[] = "algorithm"; char b[] = "altruistic"; int la = strlen(a), lb = strlen(b); cout<<DP(a, b, la, lb)<<endl; Print(la, lb); return 0; }
相关文章推荐
- 第16章 贪心算法
- 算法导论 第22章 图算法 22.3 深度优先搜索
- 算法导论-14.3-6-MIN-GAP
- 算法导论 14.1-7 顺序统计树求逆序对 O(nlgn)
- 算法导论-15-4-计划一个公司聚会
- 算法导论-13-1-持久动态集合
- Linux2.6为数据结构分配内存-slab
- 算法导论-15-7-达到最高效益的调度
- 算法导论 第10章 10.4 有根树的表示
- 算法导论 第13章 红黑树
- 算法导论 第7章 快速排序
- 算法导论 第12章 二叉查找树
- 算法导论-24.2-有向无回路图中的单源最短路径
- 算法导论 第10章 10.1 栈和队列
- 算法导论 11.1-4 大数组的直接寻址表
- 算法导论-14-1-最大重叠点
- 算法导论-12-2-基数树
- 算法导论-14-2-Josephus排列
- 算法导论-8-3-排序不同长度的数据项
- 算法导论 10.4-2 O(n)时间 递归遍历二叉树