点击打开链接题目链接
Time Limit: 2 second(s) | Memory Limit: 32 MB |
LCS means ‘Longest Common Subsequence‘ that means two non-empty strings are given; you have to find the Longest Common Subsequence between them. Since there can be many solutions, you have to print the one which is the lexicographically smallest. Lexicographical order means dictionary order. For example, ‘abc‘ comes before ‘abd‘ but ‘aaz‘ comes before ‘abc‘.
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with a blank line. The next two lines will contain two strings of length 1 to 100. The strings contain lowercase English characters only.
For each case, print the case number and the lexicographically smallest LCS. If the LCS length is 0 then just print ‘:(‘.
Sample Input |
Output for Sample Input |
3
ab ba
zxcvbn hjgasbznxbzmx
you kjhs |
Case 1: a Case 2: zxb Case 3: :( |
#include<cstdio> #include<cstring> int dp[110][110]; char str1[110],str2[110],ans[110][110][110]; int main() { int t,i,j,k; int l1,l2; while(scanf("%d",&t)!=EOF) { for(k=1;k<=t;k++) { scanf("%s",str1+1); scanf("%s",str2+1); l1=strlen(str1+1); l2=strlen(str2+1); memset(dp,0,sizeof(dp)); memset(ans,0,sizeof(ans)); for(i=1;i<=l1;i++) { for(j=1;j<=l2;j++) { if(str1[i]==str2[j]) { dp[i][j]=dp[i-1][j-1]+1; strcpy(ans[i][j],ans[i-1][j-1]); ans[i][j][dp[i-1][j-1]]=str1[i]; ans[i][j][dp[i][j]]='\0'; } else if(dp[i-1][j]>dp[i][j-1]) { strcpy(ans[i][j],ans[i-1][j]); dp[i][j]=dp[i-1][j]; } else if(dp[i-1][j]<dp[i][j-1]) { strcpy(ans[i][j],ans[i][j-1]); dp[i][j]=dp[i][j-1]; } else { dp[i][j]=dp[i][j-1]; if(strcmp(ans[i][j-1],ans[i-1][j])>0) { strcpy(ans[i][j],ans[i-1][j]); } else { strcpy(ans[i][j],ans[i][j-1]); } } } } printf("Case %d: ",k); if(dp[l1][l2]==0) { puts(":("); } else { puts(ans[l1][l2]); } } } return 0; }
LightOJ 1110 An Easy LCS LCS路径输出,布布扣,bubuko.com
LightOJ 1110 An Easy LCS LCS路径输出
原文地址:http://blog.csdn.net/qq_16843991/article/details/38678521