【Luogu P3649】[APIO2014]迴文串
阿新 • • 發佈:2021-12-08
連結:
題目大意:
給你一個由小寫拉丁字母組成的字串 \(s\)。我們定義 \(s\) 的一個子串的存在值為這個子串在 \(s\) 中出現的次數乘以這個子串的長度。
對於給你的這個字串 \(s\),求所有迴文子串中的最大存在值。
正文:
建一棵迴文樹,每一次插入字元,將當前最長迴文字尾加一,統計答案時,從後往前列舉,給失配指標的節點加上本節點的值即可。
程式碼:
const int N = 3e5 + 10; inline ll Read() { ll x = 0, f = 1; char c = getchar(); while (c != '-' && (c < '0' || c > '9')) c = getchar(); if (c == '-') f = -f, c = getchar(); while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar(); return x * f; } char s[N]; namespace PAM { int len[N], fail[N], t[N][27], s[N], cnt[N]; int tot = -1, lst, n = 0; int New (int x) { len[++tot] = x; return tot; } void Build () { fail[New(0)] = New(-1); s[0] = -1; } int Find (int x) { for (; s[n - 1 - len[x]] != s[n]; x = fail[x]); return x; } void Insert (int x) { s[++n] = x; int cur = Find(lst); if (!t[cur][x]) { int now = New(len[cur] + 2); int tmp = Find(fail[cur]); fail[now] = t[tmp][x]; t[cur][x] = now; } lst = t[cur][x]; cnt[lst]++; } ll Solve() { ll ans = 0; for (int i = tot; i; i--) cnt[fail[i]] += cnt[i]; for(int i = 1; i <= tot; i++) ans = max(ans, 1ll * len[i] * cnt[i]); return ans; } } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf ("%s", s + 1); int n = strlen (s + 1); PAM::Build(); for (int i = 1; i <= n; i++) PAM::Insert(s[i] - 'a'); printf ("%lld\n", PAM::Solve()); return 0; }