Another Meaning
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1130 Accepted Submission(s): 531
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.
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|
題意:這題題意得多看幾遍,纔好理解。 類似於:只由小寫字母構成的字符串A中的子串B可以被替換成*,問A可以生成多少個字符串。
解法: 對於每一個A的子串,如果其等於B,則有換成*和不換成*兩種情況。設dp[i]爲A串前i個字母組成的字符串可以替換生成的字符串數量,m爲字符串B的長度。如果A從第(i-m+1)到第m個字母組成的子串與B相等,若將其替換,則生成的字符串數量等於A的前i-m個字母組成的字符串生成的數量;若不替換,則等於前i-1的串生成的數量,即dp[i]=dp[i−m]+dp[i−1]。由於數據比較水,字符串匹配時strncmp之類方法就能解決,正解應該是用kmp或者hash判斷。
<span style="font-size:18px;">#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100005;
char str1[maxn],str2[maxn];
int n,sum,sum1,pos[maxn],p,dp[maxn];
const int mod=1000000007;
void pipei()
{
int i,j;
memset(pos,0,sizeof(pos));
p=0;
int len1=strlen(str1),len2=strlen(str2);
for(i=0;i<len1-len2+1;i++)
{
int ans=i,j=0;
while(j<len2 && str1[ans]==str2[j])
ans++,j++;
if(j==len2){
pos[p++]=ans-1;
}
}
}
int main()
{
int cas=0;
scanf("%d",&n);
while(n--)
{
scanf("%s %s",str1,str2);
pipei();
memset(dp,0,sizeof(dp));
dp[0]=1;
int ans=0,len2=strlen(str2),len1=strlen(str1);
for(int i=0;i<len1;i++){
if(i==pos[ans] && p){
ans++;
p--;
if(i-len2<0) dp[i]=(dp[(i-1)<0?0:(i-1)]+dp[0])%mod;
else if(i>=len2) dp[i]=(dp[i-1]+dp[i-len2])%mod;
}
else{
if(i==0) continue;
dp[i]=(dp[i-1])%mod;
}
}
printf("Case #%d: %d\n",++cas,(dp[len1-1])%mod);
}
return 0;
}</span>