题目链接:点我点我:-)
题目描述:
给一个字符串,求其本质不同的回文子串数目(字符串长度<=1000)
思路:
这是一个非常好的讲解
建立回文树,每次在最后停留的节点上计数器加一,
最后从父亲累加儿子的cnt,因为如果pre[v]=u,则u一定是v的子回文串
代码:
//miaomiao 2017.3.25
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define For(i, a, b) for(int i = (a); i <= (int)(b); ++i)
#define Forr(i, a, b) for(int i = (a); i >= (int)(b); --i)
#define N (1000+5)
char s[N];
int ans;
struct Palin_Tree{
int ch[N][30], pre[N], len[N], cnt[N], Tot, last;
void init(){
Tot = 1; last = 0;
len[1] = -1; pre[0] = 1;
}
int getfail(int id, int nl){
while(s[id-len[nl]-1] != s[id]) nl = pre[nl];
return nl;
}
void Add(int id, char c){
c -= 'a';
int nl = getfail(id, last);
if(!ch[nl][c]){
int p = ch[nl][c] = ++Tot;
len[p] = len[nl]+2;
pre[p] = ch[getfail(id, pre[nl])][c];
if(pre[p] == p) pre[p] = 0;
}
last = ch[nl][c]; ++cnt[last];
}
void Count(){
Forr(i, Tot, 2) cnt[pre[i]] += cnt[i];
For(i, 2, Tot) ans += cnt[i];
printf("%d\n", ans);
}
}PT;
int main(){
#ifndef ONLINE_JUDGE
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
#endif
PT.init();
scanf("%s", s+1); s[0] = 27;
For(i, 1, strlen(s+1)) PT.Add(i, s[i]);
PT.Count();
return 0;
}