其他分享
首页 > 其他分享> > 1346: PIPI的字符串问题Ⅳ

1346: PIPI的字符串问题Ⅳ

作者:互联网

题目描述

PIPI叒来考察大家字符串处理的能力啦。
给定一个字符串S,以及q次询问。
每次询问给出一个字符串T,你需要回答,对于T中的所有子串,有几个子串同S循环同构。
提示:对于一个字符串a,每次把a的第一个字符移动到最后一个,如果操作若干次后能够得到字符串b,则a和b循环同构。
所有字符都是小写英文字母

输入

第一行给出字符串S。|S|<=1e6.
第二行给出询问次数q,q<=1e6.
接下来每行给出字符串T,|T|<=1e6.
题目保证所有询问|T|之和<=1e7.

输出

对于每个询问,输出一个整数表示答案。

样例输入

abab
2
abababab
ababcbaba

样例输出

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);
    }
}
虱子555 发布了28 篇原创文章 · 获赞 7 · 访问量 1133 私信 关注

标签:const,int,询问,1346,给出,ull,字符串,PIPI
来源: https://blog.csdn.net/weixin_44433678/article/details/104100620