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
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.
Output
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: :( |
大意:给你两个字符串,让你输出字典序最小的最长公共子序列,没有则输出 :(
这题就是LCS的变形,普通只需要计数的LCS的递推公式是:当a[i] == b[j]时,dp[i+1][j+1] = dp[i][j] + 1,这里直接把字符加到后面就可以了,如果a[i] != b[j] 时,和计数型一样,取最长的那一个,如果长度相等的话就取字典序小的那个。
可以看出这里有很多字符串的操作,如果用字符数组存子序列的话会比较麻烦,这里用string就比较方便了。具体看代码。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int main(void)
{
int T,n,m,i,j;
string dp[110][110];
char a[110],b[110];
scanf("%d",&T);
int cas = 1;
while(T--)
{
scanf("%s%s",a,b);
n = strlen(a);
m = strlen(b);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
dp[i][j] = "";
for(i=0;i<n;i++)
for(j=0;j<m;j++)
{
if(a[i] == b[j])
dp[i+1][j+1] = dp[i][j] + a[i];
else
{
if(dp[i+1][j].size() > dp[i][j+1].size())
dp[i+1][j+1] = dp[i+1][j];
else if(dp[i+1][j].size() < dp[i][j+1].size())
dp[i+1][j+1] = dp[i][j+1];
else
{
if(dp[i+1][j] < dp[i][j+1])
dp[i+1][j+1] = dp[i+1][j];
else
dp[i+1][j+1] = dp[i][j+1];
}
}
}
printf("Case %d: ",cas++);
if(dp[n][m].size())
cout << dp[i][j];
else
printf(":(");
printf("\n");
}
}