https://www.luogu.com.cn/problem/P5496

时间复杂度:\(O(n)\)

一个由小写字母构成的字符串 \(s\),对于 \(s\) 的每个位置,求出以该位置结尾的回文子串个数。
这个字符串被进行了加密,除了第一个字符,其他字符都需要通过上一个位置的答案来解密,强制在线。

#include <bits/stdc++.h>
using namespace std;
using LL = long long;
const int N = 5e5 + 10;
string s;
struct PAM{
	int tr[N][26], fail[N], len[N], cnt[N], idx, last;
	//last 表示当前位置之前最长回文串的位置
	//cnt[i] 表示以 i 结尾的最长回文串的数量
	//fail[i] 指向 i 这个回文串的最长后缀回文串
	PAM(){
		len[0] = 0, fail[0] = 1;
		len[1] = -1, fail[1] = 0;
		idx = 1;
	}
	void insert(char c, int i){
		int p = get_fail(last, i);
		if (!tr[p][c - 'a']){
			fail[ ++ idx] = tr[get_fail(fail[p], i)][c - 'a'];
			tr[p][c - 'a'] = idx;
			len[idx] = len[p] + 2;
			cnt[idx] = cnt[fail[idx]] + 1;
		}
		last = tr[p][c - 'a'];
	}
	int get_fail(int u, int i){
		while(i - len[u] - 1 <= -1 || s[i - len[u] - 1] != s[i]){
			u = fail[u];
		}
		return u;
	}
}pam;
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin >> s;
	int n = s.length(), k = 0;
	for (int i = 0; i < n; i ++ ){
		s[i] = (s[i] - 'a' + k) % 26 + 'a';
		pam.insert(s[i], i);
		k = pam.cnt[pam.last];
		cout << k << " \n"[i == n - 1];
	}
	return 0;
}

应用:
1.本质不同的回文串个数:idx - 2
2.回文子串出现次数

posted on 2022-08-25 19:10  Hamine  阅读(159)  评论(0编辑  收藏  举报