题目:
HDU---6599:I Love Palindrome String
题意:
给定一个串,统计每个长度的回文串,并且该回文串的前一半也是回文串的数量
分析:
容易想到回文树每次添加一个字符相当于枚举回文串的右端点,跳fail指针就可以找到以当前字符为右端点的所有本质不同的回文串,题目要求前一半也为回文串,那么后一半也会是回文串,统计每个右端点的所有不同回文串的长度,就能叠加答案,但跳fail复杂度太高;回文树上每个节点代表一个本质不同的回文串,最多有N个节点,只需要判断每个本质不同的回文串是否符合条件即可统计答案;相当于判断一个串是否为回文串,这个可以马拉车或者前后两遍哈希快速判断
代码:
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn = 3e5+56;
const int base = 2333;
struct PalindromicTree{
int p,n,last,fail[maxn],tr[maxn][26],s[maxn],len[maxn],cnt[maxn],pos[maxn];
int newnode(int LEN){
for(int i = 0;i < 26; ++i) tr[p][i] = 0;
len[p] = LEN,cnt[p] = 0;
return p++;
}
void init(){
p = last = n = 0;
newnode(0),newnode(-1);
fail[0] = 1; s[0] = -1;
}
int getfail(int x){
while(s[n-len[x]-1]!=s[n])x = fail[x];
return x;
}
void add(int v,int POS){
s[++n] = v;
int cur = getfail(last);
if(!tr[cur][v]){
int now = newnode(len[cur]+2);
fail[now] = tr[getfail(fail[cur])][v];
tr[cur][v] = now;
}
last = tr[cur][v];
cnt[last]++; pos[last] = POS;
}
void count(){
for(int i = p-1; i; --i) cnt[fail[i]] += cnt[i];
}
}pt;
char s[maxn];
int ans[maxn];
ull hash1[maxn],hash2[maxn],Pow[maxn];
void gethash(int len){
hash1[0] = hash2[len+1] = 0;Pow[0] = 1;
for(int i = 1;i <= len; ++i) hash1[i] = hash1[i-1]*base+(ull)s[i],Pow[i]=Pow[i-1]*base;
for(int i = len; i ; --i) hash2[i] = hash2[i+1]*base+(ull)s[i];
}
ull gethash1(int l,int r){
return hash1[r]-hash1[l-1]*Pow[r-l+1];
}
ull gethash2(int l,int r){
return hash2[l] - hash2[r+1]*Pow[r-l+1];
}
bool check(int l,int r){
r = (l+r)>>1;
return gethash1(l,(l+r)/2) == gethash2((l+r+1)/2,r);
}
int main(){
while(~scanf("%s",s+1)){
int len = strlen(s+1); pt.init();
for(int i = 1;i <= len; ++i) pt.add(s[i]-'a',i),ans[i] = 0;
pt.count(); gethash(len);
for(int i = 2;i < pt.p; ++i){
if(check(pt.pos[i]-pt.len[i]+1,pt.pos[i]))
ans[pt.len[i]]+=pt.cnt[i];
}
for(int i = 1;i < len; ++i) printf("%d ",ans[i]);
printf("%d\n",ans[len]);
}
return 0;
}