1 //LCS模板,求长度,并记录子串
2 //亦可使用注释掉的那些代码,但所用空间会变大
3 #include<iostream>
4 #include<cstring>
5 #include<cmath>
6 #include<cstdlib>
7 #include<cstdio>
8 using namespace std;
9 #define N 5005
10
11 int len[N][N];
12 char str1[N],str2[N],str3[N];
13 int k;
14
15 int lcsLen(char *s1,int n1,char *s2,int n2)//求长度
16 {
17 for(int i=0;i<=n1;i++)
18 len[i][0]=0;
19 for(int j=0;j<=n2;j++)
20 len[0][j]=0;
21 for(int i=1;i<=n1;i++)
22 {
23 for(int j=1;j<=n2;j++)
24 {
25 if(s1[i-1]==s2[j-1])
26 len[i][j]=len[i-1][j-1]+1;
27 else
28 len[i][j]=max(len[i-1][j],len[i][j-1]);
29 }
30 }
31 return len[n1][n2];
32 }
33
34 void LCS(char *s1,char *s2,int i,int j)//递归求字串,存在tr3中
35 {
36 if(i==0||j==0)
37 return ;
38 if(s1[i-1]==s2[j-1])
39 {
40 LCS(s1,s2,i-1,j-1);
41 str3[k++]=s1[i-1];
42 }
43 else if(len[i-1][j]>=len[i][j-1])
44 LCS(s1,s2,i-1,j);
45 else
46 LCS(s1,s2,i,j-1);
47 }
48
49 void lcs(char *s1,int n1,char *s2,int n2)//求字串
50 {
51 memset(str3,0,sizeof(str3));
52 lcsLen(s1,n1,s2,n2);
53 k=0;
54 LCS(s1,s2,n1,n2);
55 }
56 int main()
57 {
58 int n1,n2;
59 while(cin >> str1 >> str2)
60 {
61 n1=strlen(str1);
62 n2=strlen(str2);
63 lcs(str1,n1,str2,n2);
64 cout << str3 << endl;
65 cout << lcsLen(str1,n1,str2,n2) << endl;
66 }
67 return 0;
68 }