zoukankan      html  css  js  c++  java
  • LCS与打印路径

    /*
        LCS
    */
    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 1000;
    int dp[maxn][maxn], c[maxn][maxn];
    int str1[maxn],str2[maxn];
    int k;
    void dfs(int i,int j){  //打印路径
        if(i == 0 || j == 0) return;
        if(c[i][j] == 1){
            dfs(i-1,j-1);
            k--;
            printf("%d%c",str1[i],k > 0 ? ' ':'
    ');
        }else if(c[i][j] == 2){
            dfs(i-1,j);
        }else{
            dfs(i,j-1);
        }
    }
    int main(){
        int n,m;
        while(scanf("%d",&n)!=EOF){
            for(int i = 1; i <= n; i++){
                scanf("%d",&str1[i]);
            }
            scanf("%d",&m);
            for(int i = 1; i <= m; i++){
                scanf("%d",&str2[i]);
            }
            for(int i = 1; i <= n; ++i){
                for(int j = 1; j <= m; j++){
                    if(str1[i] == str2[j]){
                        dp[i][j] = dp[i-1][j-1] + 1;
                        c[i][j] = 1;
                    }else if(dp[i-1][j] > dp[i][j-1]){
                        dp[i][j] = dp[i-1][j];
                        c[i][j] = 2;
                    }else{
                        dp[i][j] = dp[i][j-1];
                        c[i][j] = 3;
                    }
                }
            }
            printf("%d
    ",dp[n][m]);
            k = dp[n][m];
            dfs(n,m);
        }
        return 0;
    }
    
    /*
    7
    1 2 3 2 4 1 2
    6
    2 4 3 1 2 1
    */
    

      

  • 相关阅读:
    Day 69
    Day 68
    Day 67
    Day 66
    Day 65
    Day 64
    Day 63
    Day 62
    Day 61
    Day 60
  • 原文地址:https://www.cnblogs.com/chengsheng/p/5038619.html
Copyright © 2011-2022 走看看