1346: PIPI string problem Ⅳ

Title Description

PIPI Cheese ability to examine all string handling it.
Given a string S, and the q-th interrogation.
Each time a given query string T, you need to answer for all substrings of the T, there are several cycles substring of S isomorphic.
Note: For a string, each time a character of the first move to the last, if the operation can be several strings b, a and b are the same cyclic structure.
All characters are lowercase letters

Entry

The first line gives the string S. | S |. <= 1e6
. The second line gives the number of query q, q <= 1e6
next string of each line is given T, | T | <= 1e6 .
Title ensure that all interrogation | T | sum <= 1e7 .

Export

For each inquiry, output a integer answer.

Sample input

abab
2
abab abab
ababcbaba

Sample Output

5
2

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const ull base=23333;
const int N=1e6+5;
ull hs[2*N],pw[2*N];
char s[2*N],t[N];
unordered_map<ull,bool> mp;
main()
{
    scanf("%s",s+1);
    int n=strlen(s+1);
    for(int i=1;i<n;i++) s[n+i]=s[i]; ///扩充一倍
    pw[0]=1;
    for(int i=1;i<=2*n;i++) pw[i]=pw[i-1]*base;
    for(int i=1;i<=2*n;i++) hs[i]=hs[i-1]*base+s[i]-'a'+1; ///记录字符串扩充一倍之后哈希表的值
    for(int i=1;i<=n;i++) mp[hs[i+n-1]-hs[i-1]*pw[n]]=1; ///将长度为n的字符串映射为1,时间复杂度为O(n)
    int m;
    scanf("%d",&m);
    while(m--)
    {
        scanf("%s",t+1);
        int k=strlen(t+1),ans=0;
        if(n>k) {printf("0\n"); continue;} ///如果字符串的长度大于k,直接跳出循环,检测下一个字符串
        for(int i=1;i<=k;i++)
            hs[i]=hs[i-1]*base+t[i]-'a'+1; ///将给出的字符串哈希
        for(int i=n;i<=k;i++) if(mp.count(hs[i]-hs[i-n]*pw[n])) ans++; ///检测长度为n的子串,存在则ans++
        printf("%d\n",ans);
    }
}
Published 28 original articles · won praise 7 · views 1127

Guess you like

Origin blog.csdn.net/weixin_44433678/article/details/104100620