1. 程式人生 > >HDU 3948-The Number of Palindromes-迴文自動機

HDU 3948-The Number of Palindromes-迴文自動機

在這裡插入圖片描述

題意:

給出一個字串,求其不相同迴文子串的個數

思路:

迴文自動機模板題,因為迴文自動機中每個新建的結點就表示一個迴文子串,各個結點都不相同 所以不同迴文子串個數就是迴文自動機中新增結點個數,直接輸出即可

程式碼:

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 100005 ;
const int N = 26 ;
typedef long long LL;
struct Palindromic_Tree {
    int next[MAXN][N] ;//next指標,next指標和字典樹類似,指向的串為當前串兩端加上同一個字元構成
int fail[MAXN] ;//fail指標,失配後跳轉到fail指標指向的節點 LL cnt[MAXN] ; //表示節點i表示的本質不同的串的個數(建樹時求出的不是完全的,最後count()函式跑一遍以後才是正確的) int num[MAXN] ; //表示以節點i表示的最長迴文串的最右端點為迴文串結尾的迴文串個數 int len[MAXN] ;//len[i]表示節點i表示的迴文串的長度(一個節點表示一個迴文串) int S[MAXN] ;//存放新增的字元 int last ;//指向新新增一個字母后所形成的最長迴文串表示的節點。 int n ;//表示新增的字元個數。
int p ;//表示新增的節點個數。 int newnode ( int l ) {//新建節點 for ( int i = 0 ; i < N ; ++ i ) next[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[n] = -1 ;//開頭放一個字符集中沒有的字元,減少特判 fail[0] = 1 ; } int get_fail ( int x ) {//和KMP一樣,失配後找一個儘量最長的 while ( S[n - len[x] - 1] != S[n] ) x = fail[x] ; return x ; } void add ( int c ) { c -= 'a' ; S[++ n] = c ; int cur = get_fail ( last ) ;//通過上一個迴文串找這個迴文串的匹配位置 if ( !next[cur][c] ) {//如果這個迴文串沒有出現過,說明出現了一個新的本質不同的迴文串 int now = newnode ( len[cur] + 2 ) ;//新建節點 fail[now] = next[get_fail ( fail[cur] )][c] ;//和AC自動機一樣建立fail指標,以便失配後跳轉 next[cur][c] = now ; num[now] = num[fail[now]] + 1 ; } last = next[cur][c] ; cnt[last] ++ ; } void count () { for ( int i = p - 1 ; i >= 0 ; -- i ) cnt[fail[i]] += cnt[i] ; //父親累加兒子的cnt,因為如果fail[v]=u,則u一定是v的子迴文串! } }T; int main() { std::ios::sync_with_stdio(false); string a; int t; int ct=1; cin>>t; while(t--) { cin>>a; T.init(); int len=a.size(); for(int i=0;i<len;i++) T.add(a[i]); cout<<"Case #"<<ct++<<": "; cout<<T.p-2<<endl; //輸出新增結點個數即可 } }