Problem Description
Yes, you are developing a ‘Love calculator’. The software would be quite complex such that nobody could crack the exact behavior of the software.
So, given two names your software will generate the percentage of their ‘love’ according to their names. The software requires the following things:
The length of the shortest string that contains the names as subsequence.
Total number of unique shortest strings which contain the names as subsequence.
Now your task is to find these parts.
Input
Input starts with an integer T (≤ 125), denoting the number of test cases.
Each of the test cases consists of two lines each containing a name. The names will contain no more than 30 capital letters.
Output
For each of the test cases, you need to print one line of output. The output for each test case starts with the test case number, followed by the shortest length of the string and the number of unique strings that satisfies the given conditions.
You can assume that the number of unique strings will always be less than 263. Look at the sample output for the exact format.
Sample Input
3
USA
USSR
LAILI
MAJNU
SHAHJAHAN
MOMTAJ
Output for Sample Input
Case 1: 5 3
Case 2: 9 40
Case 3: 13 15
题目大意
给你两个串s1,s2,要求找到一个串,并且这个串的字串包含s1,s2同时要尽量使这个串的长度小,输出这个串的长度并输出方案个数(因为串不唯一)。
思路
对于所求串的长度很好理解,就是两个串的长度之和减去他们的公共字串的长度。但是对于方案个数的求法就比较复杂,可以用一个三维数组cnt[i][j]k来表示用s1串中的j个字符和s2串中的k个字符组成i个字符的串时的方案数,那么对于某种转态cnt[i][j][k]有以下两种情况:
①s1[j+1]=s2[k+1],此时cnt[i+1][j+1][k+1]+=cnt[i][j][k]。
②s1[j+1]!=s2[k+1],此时cnt[i+1][j][k+1]+=cnt[i][j][k]。
cnt[i+1][j+1][k+1]+=cnt[i][j][k]。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=30+5;
int dp[maxn][maxn],caseTime,len1,len2;
long long int cnt[2*maxn][maxn][maxn];
char s1[maxn],s2[maxn];
int LCS()
{
memset(dp,0,sizeof(dp));
for(int i=1;i<=len1;i++)
{
for(int j=1;j<=len2;j++)
{
if(s1[i]==s2[j])
{
dp[i][j]=dp[i-1][j-1]+1;
}
else
{
dp[i][j]=max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[len1][len2];
}
int cal_cnt()
{
int len=len1+len2-LCS();
memset(cnt,0,sizeof(cnt));
cnt[0][0][0]=1;
for(int i=0;i<=len;i++)
{
for(int j=0;j<=len1;j++)
{
for(int k=0;k<=len2;k++)
{
if(s1[j+1]==s2[k+1]) cnt[i+1][j+1][k+1]+=cnt[i][j][k];
else
{
cnt[i+1][j][k+1]+=cnt[i][j][k];
cnt[i+1][j+1][k]+=cnt[i][j][k];
}
}
}
}
printf("Case %d: %d %lld\n",caseTime++,len,cnt[len][len1][len2]);
}
int main()
{
caseTime=1;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s %s",s1+1,s2+1);
len1=strlen(s1+1);
len2=strlen(s2+1);
cal_cnt();
}
return 0;
}