最長公用子序列 DP,最長序列dp

來源:互聯網
上載者:User

最長公用子序列 DP,最長序列dp

演算法老師的作業,一道dp基礎題,給你兩個序列,問你最長公用子序列是什麼,比如:(a,b)是(a,c,d,b)的子序列。注意不是最長公用子串,這裡的子序列可以不連續。

兩個for迴圈就出來了,每一個dp[i][j]可以從dp[i-1][j-1]、dp[i-1][j]、dp[i][j-1]三種情況更新過來,取個最大的,然後把路徑用123存下來,最後再順著路徑找然後逆序輸出就行。

sample input:

7 4
A B C B D A B
B C D B
7 6
A B C B D A B
B D C A B A
8 4
A B C D E F G H
D C B A


#include <iostream>#include <stdio.h>#include <math.h>#include <stdlib.h>#include <string>#include <string.h>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <stack>using namespace std;typedef long long LL;const int INF=0x7fffffff;const int MAX_N=1009;char X[MAX_N],Y[MAX_N];int m,n,ct;int dp[MAX_N][MAX_N];int b[MAX_N][MAX_N];char ans[MAX_N];void solve(){    for(int i=1;i<=m;i++){        for(int j=1;j<=n;j++){            if(X[i]==Y[j]){                dp[i][j]=dp[i-1][j-1]+1;                b[i][j]=1;            }            else if(dp[i-1][j]>=dp[i][j-1]){                dp[i][j]=dp[i-1][j];                b[i][j]=2;            }            else{                dp[i][j]=dp[i][j-1];                b[i][j]=3;            }        }    }}void go_back(int x,int y){    if(x==0||y==0)return;    if(b[x][y]==1){        ans[++ct]=X[x];        return go_back(x-1,y-1);    }    if(b[x][y]==2){        return go_back(x-1,y);    }    if(b[x][y]==3){        return go_back(x,y-1);    }}int main(){    printf("輸入x和y的長度:\n");    while(scanf("%d%d",&m,&n)!=EOF){        memset(dp,0,sizeof(dp));        memset(b,0,sizeof(b));        printf("輸入序列X:\n");        for(int i=1;i<=m;i++){            scanf(" %c",&X[i]);        }//        getchar();        printf("輸入序列Y:\n");        for(int i=1;i<=n;i++){            scanf(" %c",&Y[i]);        }        solve();        printf("最長子序列長度為:%d\n",dp[m][n]);        ct=0;        go_back(m,n);        printf("最長子序列之一為:\n");        for(int i=ct;i>=1;i--){            printf("%c ",ans[i]);        }        printf("\n\n輸入x和y的長度:\n");    }    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.