最長公用子序列(LCS),最長序列lcs

來源:互聯網
上載者:User

最長公用子序列(LCS),最長序列lcs

【題目簡述】:  給定兩個字串s1s2……sn 和 t1 t2 ……tn。求出這兩個字串最長的公用給你子序列的長度。字串  s1  s2 ……sn的子序列指可以表示為si1 si2…… si n(i1 < i2 <i3<……<im)。

列如:

n  = 4;

m = 4

s   = " abcd "

t    = " becd "

輸出:

3(即:bcd)

【分析】:這個經典的最長公用子序列問題,我們可以用動態規劃來解決,我們用以下的方式來定義。

dp[ i ][ j ]  表示輸出的兩個序列的最長公用子序列的長度。

由此,這兩個子序列的公用子列可能是:

1、當 S序列的第i+1個元素同T序列的第i+1個元素相同時,便在S1 ……Si和T1……Ti的公用子列末尾追加上S(i+1)

2、s1 ……si 和 t1…… t(j+1)的公用子列。

3、s1……s(i+1)和t1 ……tj   的公用子列。

這三者中的一個,所以便可以寫出dp的遞推關係式:


即:

#include<iostream>using namespace std;int n,m;char s[1000],t[1000];int dp[1001][1001];int main(){cin>>n>>m;for(int i = 0;i<n;i++)cin>>s[i];for(int j = 0;j<m;j++)cin>>t[j];for(int i = 0;i<n;i++){for(int j = 0;j<m;j++){if(s[i] == t[j])dp[i+1][j+1] = dp[i][j] + 1;elsedp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j]);}}cout<<dp[n][m]<<endl;return 0;}



LCS(最長公用子序列)的PASCAL實現

對不起先前給了最長公用子串的,你要的題目是這個嗎Problem “已知艾爾裡斯和弟弟艾爾裡亞的基因基本相同,由於基因表達起來不方便,所以就用n個數字來表示。(因為至今共發現100000種基因,所以每個數字都<=100000)兄弟之間的基因個數是相同的,就是說他們都有n個數字。且對於每個人,這n個數字互不相同。現在要求兄弟之間基因的最長公用部分。可以不連續。”
Input 檔案LCS.IN第1行,為n(1<=n<=100000) 下面2行,每行n個數字,表示了一個人的所有基因。
Output檔案LCS.OUT一行,為他們兩人基因的最長公用部分的長度。
Sample Input Sample Output
7 3
1 2 3 4 5 6 7
7 6 5 4 1 2 3
程式給你
var n,i,j:longint;
a,b,numa,numb:array[1..100000]of longint;

procedure qsrta(h,t:longint);
var i,j,k,x,y:longint;
begin
if h>=t then exit;
k:=random(t-h+1)+h;
x:=a[k];a[k]:=a[h];a[h]:=x;
y:=numa[k];numa[k]:=numa[h];numa[h]:=y;
i:=h;j:=t;
while i<j do begin
while (i<j) and (a[j]>x) do dec(j);
if i<j then begin a[i]:=a[j];numa[i]:=numa[j];inc(i);end;
while (i<j) and (a[i]<x) do inc(i);
if i<j then begin a[j]:=a[i];numa[j]:=numa[i];dec(j);end;
end;
a[i]:=x;numa[i]:=y;
qsrta(h,i-1);qsrta(i+1,t);
end;

procedure qsrtb(h,t:longint);
var i,j,k,x,y:longint;
begin
if h>=t then exit;
k:=random(t-h+1)+h;
x:=b[k];b[k]:=b[h];b[h]:=x;
y:=numb[k];numb[k]:=numb[h];numb[h]:=y;
i:=h;j:=t;
while i<j do begin
while (i<j) and (b[j]>x) do dec(j);
if i<j then begin b[i]:=b[j];numb[i]:=numb[j];inc(i);end;
while (i<j) and (b[i]<x) do inc(i);
if i<j then begin b[j]:=b[i];numb[j]:=numb[i];dec(j);end;
end;
b[i]:=x;numb[i]:=y;
qsrtb(h,i-1);qsrtb(i+1,t);
end;

procedure qsrtnumab(h,t:longint);
var......餘下全文>>
 
matlab遞迴解最長公用子序列(LCS)問題

用遞迴不好,時間慢;遞迴是VC的做法,MATLAB與VC不同啊,它就是用矩陣來運算的;
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.