Another Meaning
As is known to all, in many cases, a word has two meanings. Such as “hehe”, which not only means “hehe”, but also means “excuse me”.
Today, ?? is chating with MeiZi online, MeiZi sends a sentence A to ??. ?? is so smart that he knows the word B in the sentence has two meanings. He wants to know how many kinds of meanings MeiZi can express.
Input
The first line of the input gives the number of test cases T; T test cases follow.
Each test case contains two strings A and B, A means the sentence MeiZi sends to ??, B means the word B which has two menaings. string only contains lowercase letters.
Limits
T <= 30
|A| <= 100000
|B| <= |A|
Output
For each test case, output one line containing “Case #x: y” (without quotes) , where x is the test case number (starting from 1) and y is the number of the different meaning of this sentence may be. Since this number may be quite large, you should output the answer modulo 1000000007.
Sample Input
4
hehehe
hehe
woquxizaolehehe
woquxizaole
hehehehe
hehe
owoadiuhzgneninougur
iehiehieh
Sample Output
Case #1: 3
Case #2: 2
Case #3: 5
Case #4: 1
HintIn the first case, “ hehehe” can have 3 meaings: “he”, “he”, “hehehe”.
In the third case, “hehehehe” can have 5 meaings: “hehe”, “he*he”, “hehe”, “**”, “hehehehe”.
Author
FZU
Source
2016 Multi-University Training Contest 4
题意:
给你一个字符串A和B,B可以表示两个意思:B和*,问你A总共可以表示多少个意思?
分析:
首先我们可以利用KMP来标记出A串中所有的匹配的初始位置。
那么每个匹配的位置有两种选择,可以变成*,或者不变
所以就对应着两种状态的转移:
初始化:dp[i] = 0;
我们设dp[i]表示前i个字符可以表示的意思的数目,那么当i不是匹配位置时,那他只能不变,即dp[i+1] += dp[i];
当是匹配的位置时,那么dp[i+Blen]也能从dp[i]状态转移过来,所以dp[i+Blen] += dp[i]。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
const int maxn = 100010;
const int mod = 1e9 + 7;
char A[maxn],B[maxn];
int fail[maxn],match[maxn],dp[maxn];
int Alen,Blen;
void getfail()
{
memset(fail,0,sizeof(fail));
fail[0] = fail[1] = 0;
for(int i=1;i<Blen;i++)
{
int j = fail[i];
while(j && B[i] != B[j]) j = fail[j];
fail[i+1] = B[i] == B[j] ? j+1 : 0;
}
}
void KMP()
{
getfail();
memset(match,0,sizeof(match));
int j = 0;
for(int i=0;i<Alen;i++)
{
while(j && A[i] != B[j]) j = fail[j];
if(A[i] == B[j]) j++;
if(j == Blen)
{
match[i-Blen+1] = 1;
j = fail[j];
}
}
}
int main()
{
int t,cas = 1;
scanf("%d",&t);
while(t--)
{
scanf("%s%s",A,B);
Alen = strlen(A); Blen = strlen(B);
KMP();
memset(dp,0,sizeof(dp));
dp[0] = 1;
for(int i=0;i<Alen;i++)
{
dp[i+1] = (dp[i+1] + dp[i]) % mod;
if(match[i]) dp[i + Blen] = (dp[i + Blen] + dp[i]) % mod;
}
printf("Case #%d: %d\n",cas++,dp[Alen]);
}
return 0;
}