小H的循环节(Hash表-字符串)

小H的循环节(Hash表-字符串)_第1张图片

字符串Hash

最近遇到了很多字符串问题,

可是我既不会后缀DC3,也不会后缀自动机,后缀树……

于是,看到题解用Hash骗,小感动一下……(能看懂题解就是很幸福的事4……求D)

这题用Hash的话可以乱搞,记得答案不能二分

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<functional>
#include<iostream>
#include<cmath>
#include<cctype>
#include<ctime>
using namespace std;
#define For(i,n) for(int i=1;i<=n;i++)
#define Fork(i,k,n) for(int i=k;i<=n;i++)
#define Rep(i,n) for(int i=0;i<n;i++)
#define ForD(i,n) for(int i=n;i;i--)
#define RepD(i,n) for(int i=n;i>=0;i--)
#define Forp(x) for(int p=pre[x];p;p=next[p])
#define Fort(i,k,t,n) for(int i=k;i<=n;i+=t) 
#define Lson (x<<1)
#define Rson ((x<<1)+1)
#define MEM(a) memset(a,0,sizeof(a));
#define MEMI(a) memset(a,127,sizeof(a));
#define MEMi(a) memset(a,128,sizeof(a));
#define INF (2139062143)
#define F (100000007)
#define MAXN (200000+10)
#define MAXT (10+10)
long long mul(long long a,long long b){return (a*b)%F;}
long long add(long long a,long long b){return (a+b)%F;}
long long sub(long long a,long long b){return (a-b+(a-b)/F*F+F)%F;}
typedef long long ll;
typedef unsigned long long ull;
const ull base=10007;
int T,n;
char s[MAXN];
ull bin[MAXN],h[MAXN]={0};
ull hash(int a,int b){if (a>b) return 0;return h[b]-h[a-1]*bin[b-a+1];}
ull link(ull a,int len2,ull b){return a*bin[len2]+b;}
bool check1(int l)
{
	bool b=0;
	Fort(i,l+1,l,n)
	{
		int len=min(l,n-i+1);
		if (h[len]^hash(i,i+len-1))
		{
			if (b) return 0;b=1;
			int l=1,r=len,ans=0;
			while (l<=r)
			{
				int m=l+r>>1;
				if (hash(i,i+m-1)==h[m]) ans=m,l=m+1;
				else r=m-1; 
			}			
			if (i+len>n) len--;
			if (link(hash(i,i+ans-1),len-ans,hash(i+ans+1,i+len))==h[len]) i++;
			else return 0; 		
		}
	}
	return 1;
}
bool check2(int l)
{
	if (l+1>=n) return 1;
	{
		int i=l+2;
		int len=min(l,n-l-1);
		{
			int l=1,r=len,ans=0;
			while (l<=r)
			{
				int m=l+r>>1;
				if (hash(i,i+m-1)==h[m]) ans=m,l=m+1;
				else r=m-1; 
			}
			if (i+ans-1==n) return 1; 			
			if (link(h[ans],len-ans,hash(ans+2,len+1))==hash(i,i+len-1 )) i+=len;
			else return 0;
		}
		for(i;i<=n;)
		{
			int len=min(l,n-i+1);
			if (hash(l+2,l+2+len-1)==hash(i,i+len-1)) i+=len; 
			else return 0;
		}
	}
	return 1;
}
int main()
{
	freopen("h.in","r",stdin);
	freopen("h.out","w",stdout);
	scanf("%d",&T);
	bin[0]=1;
	For(i,MAXN-1) bin[i]=bin[i-1]*base;
	while (T--)
	{
		scanf("%d%s",&n,s+1); h[0]=0;
		For(i,n) h[i]=h[i-1]*base+s[i];
		For(i,n)
		{
		/*	if (i==1)
			{cout<<'d'<<endl;}*/
			if (check1(i)||check2(i)) {cout<<i<<endl;break;	}
		}
	}	
	
	
	return 0;
}



你可能感兴趣的:(小H的循环节(Hash表-字符串))