算法学习:回文自动机
生活随笔
收集整理的這篇文章主要介紹了
算法学习:回文自动机
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【定義】
【自動機】
參照AC自動機
?
【前置知識】
【AC自動機】
【manacher】
其實不學這兩個也可以,但是學過之后會更方便理解
?
【解決問題】
主要解決回文串的問題
能求出? ?字符串中回文子串的長度和出現次數
?
?【算法思想】
AC自動機是建立了一個字符串字串的自動機,保存了所有子串之間的信息
信息包括,這個子串作為模式串出現的次數,這個子串的后綴之中能夠包含多少模式串
?
而回文自動機則建立了一個字符串中所有回文子串的自動機,保存了所有回文子串之間的信息
信息包括,這個回文子串的長度和出現次數,這個回文子串的后綴之中包含的其他子串
這里的回文子串和位置無關只和構成回文子串的字符有關
同AC自動機一樣,需要找到后綴中的信息,自然就需要 f a i l 指針
而這里求取 f a i l 指針時,就不單單是直接插入,而是要在 f a i l 樹上不停的跳指針
找到能夠增加的符合要求的回文子串的位置,然后擴展,
同時他的fail的建立也需要遵守這個規定
?
談談初始化和其他元素
回文自動機的初始化比較重要,因為會對后續產生比較大的影響
(我因為這個調了一天)
?
?
?
?
#include<cstdio> #include<iostream> #include<algorithm> #include<string> #define ll long long using namespace std; const int mod = 19930726; const int MAXN = 1000010; ll k; int n, cnt; int now; struct note {int son[26];ll len;int siz; }trie[MAXN]; int fail[MAXN], pos; bool operator<(note a, note b) {return a.len > b.len; } char s[MAXN]; int get(int x) {while (s[pos] != s[pos - trie[x].len - 1]) x = fail[x];return x; } void insert(int x) {int cur = get(now);if (!trie[cur].son[x]){int u = ++cnt;trie[u].len = trie[cur].len + 2;fail[u] = trie[get(fail[cur])].son[x];trie[cur].son[x] = u;}trie[trie[cur].son[x]].siz++;now = trie[cur].son[x]; } ll poww(ll a, int b) {ll res = 1;while (b){if (b & 1){res = (res*a) % mod;}a = (a*a) % mod;b = b >> 1;}return res; } void init() {fail[0] = 1; fail[1] = 0;now = 0, cnt = 1;trie[1].len = -1; } int main() {scanf("%d%lld", &n, &k);scanf("%s", s+1);init();s[0] = 0;for (pos = 1; pos <= n; pos++)insert(s[pos] - 'a');for (int i = cnt; i >= 2; i--)trie[fail[i]].siz = (trie[fail[i]].siz + trie[i].siz) % mod;//for (int i = 1; i <= cnt; i++)//printf("%lld %d\n", trie[i].len, trie[i].siz);sort(trie + 1, trie + 1 + cnt);ll ans = 1;int pos = 1;while (k){if (pos > cnt){printf("-1");return 0;}if (trie[pos].len % 2 == 0){pos++;continue;}ans = (ans*poww(trie[pos].len, k < trie[pos].siz ? k : trie[pos].siz)) % mod;k -= k < trie[pos].siz ? k : trie[pos].siz;pos++;}printf("%lld", ans);return 0; } View Code?
轉載于:https://www.cnblogs.com/rentu/p/11305837.html
總結
以上是生活随笔為你收集整理的算法学习:回文自动机的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2019.08.07【NOIP提高组】模
- 下一篇: Vue-员工管理系统