題意:求串s中每個回文串的長度與出現次數乘積的最大值。
思路:回文樹裸題,求最大的cnt*len即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <cstdlib>
#include <set>
#include <map>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;
const ll linf = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const int maxn = 300005;
const int mod = 51123987;
const int N = 26; // 字元集大小
struct Palindromic_Tree {
int nxt[maxn][N];//nxt指針,nxt指針和字典樹類似,指向的串為目前串兩端加上同一個字元構成
int fail[maxn];//fail指針,失配後跳轉到fail指針指向的節點
int cnt[maxn];//cnt[i]表示i代表的本質不同的串的個數 //結點i代表的回文串在原串中出現的次數
int num[maxn];//以節點i表示的最長回文串的最右端點為回文串結尾的回文串個數
int len[maxn];//len[i]表示節點i表示的回文串的長度
int S[maxn];//存放添加的字元
int last;//指向上一個字元所在的節點,友善下一次add
int n;//字元數組指針
int p;//節點指針/節點數
int newnode(int l) {//建立節點
for(int i = 0; i < N; ++i) nxt[p][i] = 0;
cnt[p] = 0;
num[p] = 0;
len[p] = l;
return p++;
}
void init() {//初始化
p = 0;
newnode(0);
newnode(-1);
last = 0;
n = 0;
S[0] = -1;//開頭放一個字元集中沒有的字元,減少特判
fail[0] = 1;
}
int get_fail(int x) {//和KMP一樣,失配後找一個盡量最長的
while (S[n - len[x] - 1] != S[n]) x = fail[x];
return x;
}
int add(int c) {
//c -= 'a';
S[++n] = c;
int cur = get_fail(last);//通過上一個回文串找這個回文串的比對位置
if (!nxt[cur][c]) {//如果這個回文串沒有出現過,說明出現了一個新的本質不同的回文串
int now = newnode(len[cur] + 2);//建立節點
fail[now] = nxt[get_fail(fail[cur])][c];//和AC自動機一樣建立fail指針,以便失配後跳轉
nxt[cur][c] = now;
num[now] = num[fail[now]] + 1;
}
last = nxt[cur][c];
cnt[last]++;
return last; //以添加的字元為字尾構成的最大回文串所在的節點
}
void cont() {
for (int i = p - 1; i >= 0; --i) cnt[fail[i]] += cnt[i];
//父親累加兒子的cnt,因為如果fail[v]=u,則u一定是v的子回文串!
}
}pt;
char s[maxn];
int main() {
scanf("%s", s);
int len = strlen(s);
pt.init();
for (int i = 0; i < len; ++i) {
pt.add(s[i] - 'a');
}
pt.cont();
ll ans = 1;
for (int i = 2; i < pt.p; ++i) {
ans = max(ans, (ll)pt.cnt[i] * pt.len[i]);
}
printf("%lld\n", ans);
return 0;
}