zoukankan      html  css  js  c++  java
  • hdu 1503, LCS variants, find a LCS, not just the length, backtrack to find LCS, no extra markup 分类: hdoj 2015-07-18 16:24 139人阅读 评论(0) 收藏

    a typical variant of LCS algo.
    the key point here is, the dp[][] array contains enough message to determine the LCS, not only the length, but all of LCS candidate, we can backtrack to find all of LCS.
    for backtrack, one criteria is

    dp[i-1][j]==dp[i][j]-1 && dp[i][j-1]==dp[i][j]-1

    another is

    dp[i][j]==dp[i-1][j-1]+1 && str1[i]==str2[j]

    both is ok, here the first one is used.
    //

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    
    struct myNode{ int x,y; };
    
    #define MAXSIZE 105
    int dp[MAXSIZE][MAXSIZE];
    myNode pos[MAXSIZE];
    char str1[MAXSIZE], str2[MAXSIZE];
    
    
    int main() {
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
    #endif
        int i,j,k,ch,len1,len2,len3;
        while(scanf("%s%s",str1+1, str2+1)==2) {
            len1=strlen(str1+1), len2=strlen(str2+1);
            for(i=1;i<=len1;++i) {
                for(ch=str1[i], j=1;j<=len2;++j) {
                    if(ch==str2[j]) dp[i][j]=1+dp[i-1][j-1];
                    else dp[i][j]=std::max(dp[i][j-1],dp[i-1][j]);
                }
            }
            for(i=len1, j=len2, len3=dp[len1][len2]-1;len3>=0;--len3) {
                while(1) {
                    for(k=j;len3!=dp[i][k-1];--k) {}
                    if(len3==dp[i-1][k]) {
                        pos[len3]={i,k};
                        --i, j=k-1;
                        break;
                    }
                    else {
                        --i;k=j;
                    }
                }
            }
            len3=dp[len1][len2];
            pos[len3]={len1+1,len2};
            for( i=1, j=1, k=0;k<=len3;++k,++i,++j) {
                for(;i<pos[k].x;++i) putchar(str1[i]);
                for(;j<pos[k].y;++j) putchar(str2[j]);
                putchar(str2[j]);
            }
            putchar('
    ');
        }
    
        return 0;
    }

    版权声明:本文为博主原创文章,未经博主允许不得转载。// p.s. If in any way improment can be achieved, better performance or whatever, it will be well-appreciated to let me know, thanks in advance.

  • 相关阅读:
    IE6-IE11兼容性问题列表及解决办法
    EJB--事务管理 .
    JDBC批处理---(java 对数据库的回滚) .
    redisb并发访问慢出现的问题
    redis其他问题
    多线程实现服务器端接收连接
    序列化作用
    redis的key过期时间
    nginx负载均衡和反向代理有什么区别
    nginx的负载均衡和反响代理配置
  • 原文地址:https://www.cnblogs.com/qeatzy/p/4716213.html
Copyright © 2011-2022 走看看