The Number of Palindromes
Time Limit: 3000ms
Memory Limit: 262144KB
This problem will be judged on HDU. Original ID: 394864-bit integer IO format: %I64d Java class name: Main
Now, you are given a string S. We want to know how many distinct substring of S which is palindrome.
Input
The first line of the input contains a single integer T(T<=20), which indicates number of test cases.
Each test case consists of a string S, whose length is less than 100000 and only contains lowercase letters.
Each test case consists of a string S, whose length is less than 100000 and only contains lowercase letters.
Output
For every test case, you should output "Case #k:" first in a single line, where k indicates the case number and starts at 1. Then output the number of distinct substring of S which is palindrome.
Sample Input
3 aaaa abab abcd
Sample Output
Case #1: 4 Case #2: 4 Case #3: 4
Source
解题:Palindromic Tree
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int maxn = 100010; 4 struct PalindromicTree{ 5 int son[maxn][26],fail[maxn],len[maxn],s[maxn]; 6 int tot,last,n; 7 int newnode(int slen = 0){ 8 memset(son[tot],0,sizeof son[tot]); 9 len[tot] = slen; 10 return tot++; 11 } 12 void init(){ 13 tot = last = n = 0; 14 newnode(0); 15 newnode(-1); 16 fail[0] = fail[1] = 1; 17 s[n] = -1; 18 } 19 int getFail(int x){ 20 while(s[n - len[x] -1] != s[n]) x = fail[x]; 21 return x; 22 } 23 void extend(int c){ 24 s[++n] = c; 25 int cur = getFail(last); 26 if(!son[cur][c]){ 27 int x = newnode(len[cur] + 2); 28 fail[x] = son[getFail(fail[cur])][c]; 29 son[cur][c] = x; 30 } 31 last = son[cur][c]; 32 } 33 }pt; 34 char str[maxn]; 35 int main(){ 36 int kase,cs = 1; 37 scanf("%d",&kase); 38 while(kase--){ 39 scanf("%s",str); 40 pt.init(); 41 for(int i = 0; str[i]; ++i) 42 pt.extend(str[i] - 'a'); 43 printf("Case #%d: %d ",cs++,pt.tot - 2); 44 } 45 return 0; 46 }