您的位置:首页 > 其它

zoj3818 字符串hash 求lcp

2014-09-10 15:33 337 查看
学长的代码 当模板使了

这个hash是这么算得:



所以字符串第几位到第几位可以通过公式求出来

其中x就是seed 本代码为 13331

代码中的buf就是seed的i次方

#include <cstring>
#include <cstdio>
#include <algorithm>
#include <set>
#include <map>
#define REP(i,a,b) for(int i=a;i<b;i++)
#define RREP(i,a,b) for(int i=a;i>b;i--)
#define lson num<<1
#define rson num<<1|1
#define gl l,(l+r)>>1,lson
#define gr ((l+r)>>1)+1,r,rson
using namespace std;

const int MAX_N = 55;
char s[MAX_N];
int len;
struct HASH
{
long long buf[MAX_N];
long long hl[MAX_N];
const int SEED = 13331;
void init(char *s)
{
len=strlen(s);
hl[len]=0;
buf[0]=1;
RREP(i,len-1,-1)
{
hl[i]=hl[i+1]*SEED+s[i];
buf[len-i]=buf[len-i-1]*SEED;
}
}
long long hash(int i,int L)
{
return hl[i]-hl[i+L]*buf[L];
}
int Find_lcp(int i,int j)
{
int l=0,r=min(len-i,len-j);
int res=0;
while (l<=r)
{
int mid=(l+r)/2;
if (hash(i,mid)==hash(j,mid))
{
res=mid;
l=mid+1;
}
else r=mid-1;
}
return res;
}
bool ABABA(int n)
{
REP(i,1,n)
{
int l=min(Find_lcp(0,i),i);
if (l==i&&n-i-l<l)
{
int k=Find_lcp(0,i+l);
k=min(k,n-i-l);
if (k>0&&k<l&&k==n-i-l)
{
if (hash(0,k)!=hash(k,l-k)) return true;
}
}
}
return false;
}

bool ABABCAB(int n)
{
REP(i,2,n)
{
int l=min(Find_lcp(0,i),i);
if (l==i&&i+l<n-l)
{
int k=Find_lcp(0,n-l);
if (k>0&&k==l)
{
bool ok=false;
REP(p,1,i)
{
if (hash(0,p)!=hash(p,i-p)&&hash(0,p)!=hash(i+l,n-l-i-l)&&hash(p,i-p)!=hash(i+l,n-l-i-l))
{
ok=true;
break;
}
}
if (ok) return true;
}
}
}
return false;
}
} hash;

int init(char *s)
{
int n=0;
for (int i=0; s[i]; i++)
if ((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z'))
s[n++]=s[i];
s
=0;
//puts(s);
return n;
}

int main()
{
int T;
scanf("%d",&T);
while (T--)
{
scanf("%s",s);
init(s);
hash.init(s);
if (hash.ABABA(len)) printf("Yes\n");
else if (hash.ABABCAB(len)) printf("Yes\n");
else printf("No\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: