HDU5157 Harry and magic string(迴文樹)
阿新 • • 發佈:2018-12-18
題意:從一個串s中取兩個迴文子串,求使兩個迴文串互不相交的取法數。
#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 = 100005; const int mod = 1000000007; 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; ll ans; ll qz[maxn]; // qz[i]:第i位之前的迴文串數 char s[maxn]; int main() { while (~scanf("%s", s + 1)) { pt.init(); int len = strlen(s + 1); qz[0] = ans = 0; for (int i = 1; i <= len; ++i) { qz[i] = qz[i - 1] + pt.num[pt.add(s[i] - 'a')]; } pt.init(); for (int i = len; i >= 1; --i) { ans += pt.num[pt.add(s[i] - 'a')] * qz[i - 1]; } printf("%lld\n", ans); } return 0; }