ZOJ 4030 第15屆浙江省賽
JUMPin' JUMP UP!!!
Tired of solving mathematical equations, DreamGrid starts to solve equations related to strings: for two strings and with the same length consisting of lowercase English letters, calculate , which is defined as the number of nonempty strings consisting of lowercase English letters such that and the length of does not exceed .
DreamGrid has two strings and . He would like to ask several questions about the value of , where is the substring of starting from with length and is a given number.
Input
There are multiple test cases. The first line of input contains an integer , indicating the number of test cases. For each test case:
The first line contains three integers and and () -- the length of , the length of and the number of questions.
The second line contains lowercase English letters denoting the string . The third line contains lowercase English letters denoting the string .
Each of the next lines contains two integers and () denoting the -th question.
It is guaranteed that neither the sum of all nor the sum of all exceeds .
Output
For each question, output an integer denoting the answer.
Sample Input
1 4 2 3 abcd ba 1 2 2 2 3 2
Sample Output
1 0 0
題目大意:
兩個字串x,y,和另一個字串z,若xz=zy,則稱x,y在z下匹配。現在已知兩個字串x,y,求多少個z能使之匹配(|z|<LIMIT).
題解:
Z的長度為2,2+4,2+4+4,都可以,所以求出斷點後,加上某個數的倍數都可以。
暴力短串的斷點,將m種情況用hash存下來。
(每種情況都有無數種方案c,c+k,c+2k,C+3k……)
對於每個詢問,判斷hash中是否存在,再輸出可行的方案數目。(有長度限制的緣故)。字典序hash會被卡掉,所以要用2種模數來判斷
程式碼:
#include<bits/stdc++.h>
#define N 100010
#define LL long long
using namespace std;
char s2[N],s1[N];
LL p[N],H1[N],H2[N],h1[N],h2[N],pp[N];
int a[N],next[N];
const LL P=99959;
const LL MOD=100001651;
const LL MmOD=100001611;
typedef pair<LL,LL> PP;
map<PP,int>s;
int main()
{
int T,n,m,q,cnt,j,v; LL t; long long k;
p[0]=1;pp[0]=1;for (int i=1;i<N;i++) p[i]=p[i-1]*P%MOD,pp[i]=pp[i-1]*P%MmOD;
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d%s%s",&n,&m,&q,s1+1,s2+1);
next[0]=-1;
for (int i=1;i<=m;i++)
{
int p=next[i-1];
while (p>=0 && s2[p+1]!=s2[i]) p=next[p];
next[i]=p+1;
}
int qq=m-next[m];if (next[m]*2<m) qq=m;
s.clear();
H1[0]=H1[1]=0;h1[0]=h1[1]=0;
for (int i=1;i<=m;i++) H1[1]=(H1[1]*P+(s1[i]-'a'+1))%MOD,
h1[1]=(h1[1]*P+(s1[i]-'a'+1))%MmOD;
for (int i=m+1;i<=n;i++) H1[i-m+1]=((((H1[i-m]-p[m-1]*(s1[i-m]-'a'+1)%MOD)+MOD)%MOD)*P%MOD+(s1[i]-'a'+1))%MOD,
h1[i-m+1]=((((h1[i-m]-pp[m-1]*(s1[i-m]-'a'+1)%MmOD)+MmOD)%MmOD)*P%MmOD+(s1[i]-'a'+1))%MmOD;
H2[0]=0;h2[0]=0;for (int i=1;i<=m;i++) H2[i]=(H2[i-1]*P+(s2[i]-'a'+1))%MOD,
h2[i]=(h2[i-1]*P+(s2[i]-'a'+1))%MmOD;
cnt=0;LL tt;
for (int i=1;i<=m;i++)
{
t=((((H2[m]-H2[i]*p[m-i]%MOD)+MOD)%MOD)*p[i]+H2[i])%MOD;
tt=((((h2[m]-h2[i]*pp[m-i]%MmOD)+MmOD)%MmOD)*pp[i]+h2[i])%MmOD;
if (!s[PP(t,tt)]) s[PP(t,tt)]=++cnt,a[cnt]=i;
}
while (q--)
{
scanf("%d%lld",&j,&k);
t=H1[j]; tt=h1[j];
v=s[PP(t,tt)];
if(!s[PP(t,tt)])puts("0");else printf("%lld\n",(k-a[v]+qq)/qq);
}
}
}