zoukankan      html  css  js  c++  java
  • 动态规划——LCS

    LCS代码实现

    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #define maxn 105
    using namespace std;
    char a[maxn],b[maxn];
    int dp[maxn][maxn];
    int LCSlength() {
        memset(dp,0,sizeof(dp));
        int alen = strlen(a);
        int blen = strlen(b);
        for(int i=0; i<alen; i++) {
            for(int j=0; j<blen; j++) {
                if(a[i]==b[j]) {
                    dp[i][j] = dp[i-1][j-1]+1;
                } else {
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return dp[alen-1][blen-1];
    }
    int main() {
        while(~scanf("%s %s",a,b)) {
            int ans = LCSlength();
            printf("%d",ans); 
        }
    
        return 0;
    }
    View Code

     递归求LSC序列:

    #include<iostream>
    #include<cstring>
    #include<algorithm>
    #define maxn 105
    using namespace std;
    char a[maxn],b[maxn];
    int dp[maxn][maxn];
    int step[maxn][maxn];
    void Print(int i,int j){
        if(i<0 || j<0){
            return;
        }
        if(step[i][j]==1){
            Print(i-1,j-1);
            printf("%c",a[i]); 
        }else if(step[i][j]==2){
            Print(i-1,j);
        }else if(step[i][j]==3){
            Print(i,j-1);
        }
    }
    void LCS(){
        memset(dp,0,sizeof(dp));
        int alen = strlen(a);
        int blen = strlen(b);
        for(int i=0;i<alen;i++){
            for(int j=0;j<blen;j++){
                if(a[i]==b[j]){
                    dp[i][j] = dp[i-1][j-1]+1;
                    step[i][j] = 1;
                }else{
                    if(dp[i-1][j]>dp[i][j-1]){
                        dp[i][j] = dp[i-1][j];
                        step[i][j] = 2;
                    }else{
                        dp[i][j] = dp[i][j-1];
                        step[i][j] = 3;
                    }
                }
            }
        }
        cout<<dp[alen-1][blen-1]<<endl;
        Print(alen-1,blen-1);
    }
    int main() {
        while(~scanf("%s %s",a,b)) {
            LCS();
            
        }
    
        return 0;
    }
    View Code

    非递归LSC序列:

  • 相关阅读:
    cssReset
    CSS的一些小技巧
    前端图标神器
    单例模式
    CSS 控制Html页面高度导致抖动问题的原因
    PHP中include()与require()的区别说明
    extends和implements区别
    静态,抽象类、接口、类库
    jQuery轮播图(手动点击轮播)
    jQuery实现大图轮播
  • 原文地址:https://www.cnblogs.com/Lemon1234/p/11772645.html
Copyright © 2011-2022 走看看