给出两个字符串,然后给出一个串要求包含两个串,并且最短...
依然用LCS找出最长序列后,然后依次把其他部分加进去,special judge ,问题简单了...
1 #include <stdio.h>
2 #include <string.h>
3 #include <memory.h>
4 #define MAX(a,b) (a)>(b)?(a):(b)
5 char str1[120],str2[120];
6 char lcs[120],result[220];
7 int dp[105][105];
8 int main()
9 {
10
11 while(scanf("%s%s",str1+1,str2+1)!=EOF)
12 {
13 int len1=strlen(str1+1),len2=strlen(str2+1);
14 memset(dp,0,sizeof(dp));
15 for(int i=1;i<=len1;i++)
16 for(int j=1;j<=len2;j++)
17 {
18 if(str1[i]==str2[j])dp[i][j]=dp[i-1][j-1]+1;
19 else dp[i][j]=MAX(dp[i-1][j],dp[i][j-1]);
20
21 }
22 if(dp[len1][len2]==0)printf("%s%s\n",str1+1,str2+1);
23 else
24 {
25 int t=1,m=1,n=1,k=0;
26 for(int i=len1;i>0;)
27 for(int j=len2;j>0;)
28 {
29 if(dp[i][j]==dp[i-1][j])i--;
30 else if(dp[i][j]==dp[i][j-1])j--;
31 else
32 {
33 lcs[t]=str1[i];
34 t++;i--;j--;
35 }
36
37 }
38
39 lcs[t]='\0';
40 //printf("%d k=%d %s\n",dp[len1][len2],t,lcs+1);
41 for(int i=dp[len1][len2];i>0;i--)
42 {
43 while(str1[m]!=lcs[i]&&m<=len1){result[k++]=str1[m];m++;}
44 while(str2[n]!=lcs[i]&&n<=len2){result[k++]=str2[n];n++;}
45 result[k++]=lcs[i];m++;n++;
46 }
47 result[k]='\0';
48 if(m-1<len1)strcat(result,str1+m);
49 if(n-1<len2)strcat(result,str2+n);
50 printf("%s\n",result);
51 }
52 }
53 return 0;
54 }