题解:
循环同构要求长度一样,因此可以求出T的每个循环同构的has值,
然后对于输入的t,求出每个长度为strlen(T)的子串的has值,判断
他在T中是否存在即可。
开始的时候has值用map存的,因为每次查找都要log(n)的效率,
超时了,所以用了head指针,用mod以内的数映射所有x.
注:因为这样的时间复杂度极不稳定,有时需要调整mod的值来尝试
比如这题:
mod=1007超时
mod=10007 146ms
mod=100007 96ms
mod=10050007 426ms
因此如果代码超时可以通过调整mod的值不断尝试。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
const int maxn=2e6+7;
const int mod=100007;
const ull base=123;
char t[maxn];
ull h[maxn],has[maxn];
int head[mod],tol=0;
struct node
{
ull to;
int next;
}rode[maxn];
void add(ull x)
{
int pos=x%mod;
rode[tol].to=x;
rode[tol].next=head[pos];
head[pos]=tol++;
}
int find(ull x)
{
int pos=x%mod;
for(int i=head[pos];i!=-1;i=rode[i].next)
if(rode[i].to==x)return 1;
return 0;
}
int main()
{
scanf("%s",t+1);
int L=strlen(t+1);
memset(head,-1,sizeof(head));
for(int i=1;i<=L;i++)
t[i+L]=t[i];
h[0]=1;
for(int i=1;i<maxn;i++)
h[i]=h[i-1]*base;
has[0]=0;
for(int i=1;i<=2*L;i++)
{
has[i]=has[i-1]*base+t[i];
if(i>=L) add(has[i]-has[i-L]*h[L]);
}
int T;scanf("%d",&T);
while(T--)
{
scanf("%s",t+1); int l=strlen(t+1),ans=0;
for(int i=1;i<=l;i++)
{
has[i]=has[i-1]*base+t[i];
if(i>=L) ans+=find(has[i]-has[i-L]*h[L]);
}
printf("%d\n",ans);
}
return 0;
}
牛客hash字符串(求循环同构)
最新推荐文章于 2020-08-15 19:19:51 发布