Time Limit: 2 second(s) | Memory Limit: 32 MB |
LCS means 'Longest Common Subsequence' that means two non-empty strings are given; the longest subsequence that are common. Subsequence means removing 0 or more characters from a string.
Now you are given two non-empty strings s and t, your task is to find the number of distinct LCS of s and t. Since the result can be very big, print the result modulo 1000007.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains two lines, the first line is the string s and the second line is the string t. You may assume that the strings are non-empty and consist only of lowercase letters and the length of the each string is at most 1000.
Output
For each case, print the case number and the number of distinct LCS of s and t modulo 1000007.
Sample Input | Output for Sample Input |
4 acbd acbd vnvn vn ab ba xyz abc | Case 1: 1 Case 2: 1 Case 3: 2 Case 4: 1 |
/*
参考:http://www.xuebuyuan.com/zh-tw/2100947.html
*/
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-8
typedef long long ll;
using namespace std;
#define mod 1000007
#define INF 0x3f3f3f3f
#define N 1005
int f[N][N],dp[N][N];
int len,lena,lenb;
char a[N],b[N];
int last1[N][N];
int last2[N][N];
void inint()
{
int i,j;
memset(dp,0,sizeof(dp));
for(i=1;i<=lena;i++)
for(j=1;j<=lenb;j++)
if(a[i]==b[j])
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
void pre()
{
int i,j;
memset(last1,0,sizeof(last1));
memset(last2,0,sizeof(last2));
for(int i=1;i<=lena;i++)
for(char c='a';c<='z';c++)
{
last1[i][c]=last1[i-1][c];
if(a[i]==c)
last1[i][c]=i;
}
for(int i=1;i<=lenb;i++)
for(char c='a';c<='z';c++)
{
last2[i][c]=last2[i-1][c];
if(b[i]==c)
last2[i][c]=i;
}
}
int dfs(int lena,int lenb,int len)
{
if(len<=0) return 1;
if(f[lena][lenb]!=-1) return f[lena][lenb];
int ans=0;
if(lena>0&&lenb>0)
{
for(char c='a';c<='z';c++)
{
int t=last1[lena][c];
int tt=last2[lenb][c];
if(dp[t][tt]>=len)
ans+=dfs(t-1,tt-1,len-1);
ans%=mod;
}
}
return f[lena][lenb]=ans;
}
int main()
{
int i,j,t,ca=0;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",a+1,b+1);
lena=strlen(a+1);
lenb=strlen(b+1);
inint();
pre();
memset(f,-1,sizeof(f));
printf("Case %d: %d\n",++ca,dfs(lena,lenb,dp[lena][lenb]));
}
return 0;
}