題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=6599
解題心得:
- 其實看到這個迴文串計數問題就該想到迴文樹,用迴文樹得到每一個相同種類迴文串的數量,在或者判斷一下是否前一半也是迴文串就行了。
- 比賽的時候這麼多人都會迴文樹也tql吧,都是些什麼神仙啊,氣餒。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 6e5+100;
char ch[maxn];
int ans[maxn];
struct Palindromic_Tree {
int next[maxn][30] ;//next指針,next指針和字典樹類似,指向的串爲當前串兩端加上同一個字符構成
int fail[maxn] ;//fail指針,失配後跳轉到fail指針指向的節點
int cnt[maxn] ;
int num[maxn] ;
int len[maxn] ;//len[i]表示節點i表示的迴文串的長度
int s[maxn] ;//存放添加的字符
int last ;//指向上一個字符所在的節點,方便下一次add
int n ;//字符數組指針
int tot ;//節點指針
int endpoint[maxn];
int newnode(int Len) {
memset(next[tot], 0, sizeof(next[tot]));
cnt[tot] = 0;
len[tot] = Len;
num[tot] = 0;
return tot++;
}
void init() {
tot = 0;
newnode(0);
newnode(-1);
last = 0,
n = 0;
fail[0] = 1, fail[1] = 0;
s[n] = -1;
}
int get_fail(int p) {
while(s[n - len[p] -1] != s[n]) p = fail[p];
return p;
}
void insert(int c, int pos) {
s[++n] = c;
int cur = get_fail(last);
if(next[cur][c] == 0) {
int now = newnode(len[cur] + 2);
fail[now] = next[get_fail(fail[cur])][c];
next[cur][c] = now;
num[now] = num[fail[now]] + 1;
}
last = next[cur][c];
cnt[last]++;
endpoint[last] = pos;
}
void add_cnt() {
for(int i=tot-1;i>0;i--) {
cnt[fail[i]] += cnt[i];
}
}
};
struct Hash {
unsigned long long p[maxn], hash[maxn], base = 233;
void init(char s[], int k) {
p[0] = 1;
hash[0] = 0;
for(int i=1;i<=k;i++) p[i] = p[i-1] * base;
for(int i=1;i<=k;i++) hash[i] = hash[i-1]*base + s[i] - 'a' + 1;
}
unsigned long long equal(int l,int r) {
return hash[r] - hash[l-1] * p[r-l+1];
}
};
Palindromic_Tree pam;
Hash hash1, hash2;
bool checke(int pos, int len, int Len) {
int r = pos, l = pos-len+1;
int r1 = Len-l+1, l1 = Len-r+1;
return hash1.equal(l, r) == hash2.equal(l1, r1);
}
int main() {
// freopen("1.in.txt", "r", stdin);
while(scanf("%s", ch+1) != EOF ) {
pam.init();
memset(ans, 0, sizeof ans);
int len = strlen(ch+1);
for(int i=1;i<=len;i++) {
ans[i] = 0;
pam.insert(ch[i]-'a', i);
}
pam.add_cnt();
hash1.init(ch, len);
reverse(ch+1, ch+1+len);
hash2.init(ch, len);
for(int i=2;i<pam.tot;i++) {
int cntlen = pam.len[i];
int pos = pam.endpoint[i];
if(checke(pos - cntlen/2, (cntlen+1)/2, len)) {
ans[cntlen] += pam.cnt[i];
}
}
for(int i=1;i<=len;i++) {
printf("%d", ans[i]);
if(i != len) printf(" ");
}
printf("\n");
}
return 0;
}