题意:求每读入一个字符,对答案贡献了多少个本质不同的回文串。
思路:我们知道回文自动机上每个节点就代表不同的回文串,所以统计节点数即可。
代码:
#include <cstdio> #include <cstring> const int MAX_N = 600005; const int SIG = 26 ; struct PTree { int nxt[MAX_N][SIG], fail[MAX_N], cnt[MAX_N], num[MAX_N], len[MAX_N], S[MAX_N]; int last, n, p; int newNode (int l) { memset(nxt[p], 0, sizeof nxt[p]); cnt[p] = num[p] = 0; len[p] = l; return p++; } void init() { p = last = n = 0; newNode(0), newNode(-1); S[n] = -1; fail[0] = 1; } int getFail(int x) { while (S[n - len[x] - 1] != S[n]) x = fail[x]; return x; } int add(int c) { c -= 'a'; S[++n] = c; int cur = getFail(last); if (!nxt[cur][c]) { int now = newNode(len[cur] + 2); fail[now] = nxt[getFail(fail[cur])][c]; nxt[cur][c] = now; num[now] = num[fail[now]] + 1; } last = nxt[cur][c]; ++cnt[last]; return p - 2; } void count() { for (int i = p - 1; i >= 0; --i) cnt[fail[i]] += cnt[i]; } }; PTree T; char s[MAX_N]; int main() { while (1 == scanf("%s", s)) { T.init(); for (int i = 0; s[i]; ++i) { if (i == 0) printf("%d", T.add(s[i])); else printf(" %d", T.add(s[i])); } puts(""); } return 0; }