【回文自动机】 BZOJ 2565 最长双回文串
题意:求最长不相交双回文串
思路:dp1[i]表示[1,i]的回文串,dp2[i]表示[i+1,len]的回文串,ans=max(dp1[i]+dp2[i]);
代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; 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; } void add(int c, int pos, int *dp) { 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]; dp[pos] = len[last]; } void count() { for (int i = p - 1; i >= 0; --i) cnt[fail[i]] += cnt[i]; } }; PTree T; char s[MAX_N]; int dp1[MAX_N], dp2[MAX_N]; int main() { while (1 == scanf("%s", s)) { T.init(); for (int i = 0; s[i]; ++i) T.add(s[i], i, dp1); T.init(); int len = strlen(s); for (int i = len - 1; i >= 0; --i) T.add(s[i], len - 1 - i, dp2); int ans = 2; for (int i = 0; i + 1 < len; ++i) { ans = max(ans, dp1[i] + dp2[len - i - 2]); } printf("%d\n", ans); } return 0; }