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 ? ' ':'\n');
    }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\n",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
*/

  

posted @ 2015-12-11 12:16  tcgoshawk  阅读(225)  评论(0编辑  收藏  举报