Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1503
Test instructions: Constructs another string from two strings that contains the first two strings (in character order but not necessarily consecutively) to minimize the length of the string
Analysis: Dp[i][j] represents the longest common substring of s1[0-i] and s2[0-j]. Use the digital flag to record the path and back out the answer.
#include <cstdio>#include<cstring>#include<cmath>#include<iostream>#include<algorithm>#include<queue>#include<cstdlib>#include<vector>#include<Set>#include<map>#defineLL Long Long#defineMoD 1000000007#defineINF 0x3f3f3f3f#defineN 10010using namespacestd;Chars1[ the],s2[ the];intdp[ the][ the],flag[ the][ the];voidPrintintXinty) { if(x==0&&y==0)return; if(flag[x][y]==0) {print (x-1, Y1); printf ("%c", s1[x-1]); } Else if(flag[x][y]==1) {print (x, y-1); printf ("%c", s2[y-1]); } Else{print (x-1, y); printf ("%c", s1[x-1]); }}intMain () { while(SCANF ("%s%s", S1,S2) >0) { intlen1=strlen (S1); intLen2=strlen (S2); Memset (DP,0,sizeof(DP)); for(intI=0; i<=len1;i++) flag[i][0]=-1;;//This moment s1[i] to lose alone for(intI=0; i<=len2;i++) flag[0][i]=1;;//This moment s2[i] to lose alone for(intI=1; i<=len1;i++) for(intj=1; j<=len2;j++) { if(s1[i-1]==s2[j-1]) {Dp[i][j]=dp[i-1][j-1]+1; FLAG[I][J]=0;//indicates that this moment belongs to the public part } Else if(dp[i][j-1]<dp[i-1][j]) {Dp[i][j]=dp[i-1][j]; FLAG[I][J]=-1;//This moment s1[i-1] to lose alone } Else{Dp[i][j]=dp[i][j-1]; FLAG[I][J]=1;//This moment s2[j-1] to lose alone}} print (LEN1,LEN2);p UTS (""); }}View Code
hdu1503 (longest common sub-sequence)