HDU-5340 Three Palindromes(字符串哈希)

http://acm.hdu.edu.cn/showproblem.php?pid=5340

orz到了新的字符串hash姿势

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#define rep(i,l,r) for (int i=l;i<=r;i++)
#define maxn 200500
#define p 1000000007
using namespace std;
typedef unsigned long long ll;
ll a[maxn],b[maxn],k[maxn];
int c[maxn],d[maxn],t1,t2,cnt,n,t;
char s[maxn];
int main(){
scanf("%d",&t);
k[0]=1;
rep(i,1,20000) k[i]=k[i-1]*p;
while (t--){
scanf("%s",s+1);
n=strlen(s+1);
t1=t2=cnt=b[n+1]=0;
for (int i=1;i<=n;i++) a[i]=a[i-1]*p+s[i];
for (int i=n;i>=1;i--) b[i]=b[i+1]*p+s[i];
for (int i=1;i<=n;i++){
ll h=b[1]-b[i+1]*k[i];
if (h==a[i]) c[++t1]=i;
h=a[n]-a[n-i]*k[i];
if (h==b[n-i+1]) d[++t2]=n-i+1;
}
reverse(c+1,c+1+t1);
int l,r,flag=0;
rep(i,1,t1){
if (flag) break;
rep(j,1,t2){
l=c[i]+1; r=d[j]-1;
if (l>r||cnt>2e6) break;
++cnt;
ll h1=a[r]-a[l-1]*k[r-l+1];
ll h2=b[l]-b[r+1]*k[r-l+1];
if (h1==h2) flag=1;
}
}
if (flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}

posted on 2015-08-01 23:14  ctlchild  阅读(361)  评论(1编辑  收藏  举报

导航