# HDU 1503, LCS variants, find a LCS, not just the length, backtrack to find LCS, no extra markup

Source: Internet
Author: User

A typical variant of LCS Algo.
The key, the dp[][] array contains enough message to determine the LCS, not only the length, but all of the LCS Candidate, we can backtrack to the 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, this first one is used.
//

``#include <cstdio>#include <cstring>#include <algorithm>structmynode{intx, y; };#define MAXSIZEintDp[maxsize][maxsize];mynode Pos[maxsize];CharStr1[maxsize], str2[maxsize];intMain () {#ifndef Online_judgeFreopen ("In.txt","R", stdin);#endif    intI,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];Elsedp[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(' \ n '); }return 0;}``

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced. Ps. If in any-to-improment can be achieved, better performance or whatever, it'll be well-appreciated-let me know, thank s in advance.

HDU 1503, LCS variants, find a LCS, not just the length, backtrack to find LCS, no extra markup

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## 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.