当前位置: 代码迷 >> 综合 >> The Number of Palindromes HDU - 3948 (回文树)
  详细解决方案

The Number of Palindromes HDU - 3948 (回文树)

热度:29   发布时间:2024-01-14 22:17:12.0

题目 https://cn.vjudge.net/problem/HDU-3948

题意

求出本质不同的回文串个数。

思路 回文树

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 210005 ;
const int N = 26 ;struct Palindromic_Tree {int next[MAXN][N] ;//next指针,next指针和字典树类似,指向的串为当前串两端加上同一个字符构成int fail[MAXN] ;//fail指针,失配后跳转到fail指针指向的节点long long cnt[MAXN] ;//cnt[i]表示节点i表示的本质不同的串的个数(建树时求出的不是完全的,最后count()函数跑一遍以后才是正确的)int num[MAXN] ; //num[i]表示以节点i表示的最长回文串的最右端点为回文串结尾的回文串个数int len[MAXN] ;//len[i]表示节点i表示的回文串的长度int S[MAXN] ;//存放添加的字符int last ;//指向上一个字符所在的节点,方便下一次addint 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 ;//  cout<<n<<" "<<(char)(S[n]+'a')<<endl;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的子回文串!}
} ;
Palindromic_Tree a1,b1;
long long ans;
char a[201312],b[223123];int main()
{int T;cin>>T;int yy =0;int cn = 1;while(T--){scanf("%s",a);yy++;int len1 =strlen(a);a1.init();for(int i=0;i<len1;i++){a1.add(a[i]);}printf("Case #%d: %d\n",cn++,a1.p-2);}return 0;
}

 

  相关解决方案