演算法導論-15-3-編輯距離

來源:互聯網
上載者:User

題目:

思考:

(1)初始化:

s[0,0]=0

s[i,0] = i * cost(delete)

s[0,j] = j * cost[insert]

(2)遞推

(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,killint 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];//DPfor(i = 0; i < lx; i++){for(j = 0; j < lz; j++){s[i+1][j+1] = 0x7fffffff;//copyif(x[i] == z[j]){temp = s[i][j] + cost[0];if(temp < s[i+1][j+1])s[i+1][j+1] = temp;}//replaceif(x[i] != z[j]){temp = s[i][j] + cost[1];if(temp < s[i+1][j+1])s[i+1][j+1] = temp;}//deletetemp = s[i][j+1] + cost[2];if(temp < s[i+1][j+1])s[i+1][j+1] = temp;//inserttemp = s[i+1][j] + cost[3];if(temp < s[i+1][j+1])s[i+1][j+1] = temp;//twidleif(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;}}}//killint 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.