Time Limit: 2 second(s) | Memory Limit: 32 MB |
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:
1. The length of the shortest string that contains the names as subsequence.
2. 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 | Output for Sample Input |
3 USA USSR LAILI MAJNU SHAHJAHAN MOMTAJ | Case 1: 5 3 Case 2: 9 40 Case 3: 13 15 |
题目大意:
给两个字符串,求长度最短的字符串的长度以及个数,使得给出的两个串都是这个串的子串。
题目分析:
LCS的变形,首先长度自然是len(s1)+len(s2)-len(LCS)。关键是有多少个这样的字符串。
如图: 转自------->http://blog.csdn.net/DrCarl/article/details/52164155
代码如下:
在经过自己的脑补之后,写了一些注释,不知道对不对。哪位大大看到哪错啦,就评论一下哦。欢迎指错。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL cnt[33][33];//表示长度为i的串与长度为j的串组成的方法数
int dp[33][33];//用来计算LCS最长公共子序列
int main()
{
int t,cas=1;
scanf("%d",&t);
while(t--)
{
char s1[33],s2[33];
memset(dp,0,sizeof(dp));
memset(cnt,0,sizeof(cnt));
scanf(" %s %s",s1+1,s2+1);
//由s1与s2时是组成串的子串,需要按字符的顺序排序,若两字符为公共字符则只需要插入一个字符,否则需要插入两个字符
int n=strlen(s1+1),m=strlen(s2+1);
//将cnt数组初始化,在另一个串长度为0时,组成方法只有一种。
for(int i=0;i<=n;i++) cnt[i][0]=1;
for(int i=0;i<=m;i++) cnt[0][i]=1;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
if(s1[i]==s2[j])//若两字符串字符相等,说明该字符为两个串公共字符
{
//则LCS在dp[i-1][j-1]基础上+1
dp[i][j]=dp[i-1][j-1]+1;
//由于新加入的字符为公共字符,只需要插入一个字符在末尾
cnt[i][j]=cnt[i-1][j-1]; //即组成方法与cnt[i-1][j-1]相同
}
else
{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
//在dp[i-1][j]!=dp[i][j-1]时,在s1[i]与s2[j]中有一个字符为两个串的公共字符,也只需要插入一个字符
if(dp[i-1][j]>dp[i][j-1]) cnt[i][j]=cnt[i-1][j];//则第i个字符不是公共字符,按顺序插入最后
else if(dp[i-1][j]<dp[i][j-1]) cnt[i][j]=cnt[i][j-1];//则第j个字符不是公共字符,按顺序插入最后
//在相等时说明这两个字符都目前不是公共字符,需要把添加这两个字符时的方法相加
else cnt[i][j]=cnt[i][j-1]+cnt[i-1][j];
}
}
printf("Case %d: %d %lld\n",cas++,n+m-dp[n][m],cnt[n][m]);
}
return 0;
}