您的位置:首页 > 其它

HDU 3948 The Number of Palindromes

2015-10-27 13:33 537 查看

The Number of Palindromes

Time Limit: 3000ms
Memory Limit: 262144KB
This problem will be judged on HDU. Original ID: 3948
64-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.

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

2011 Multi-University Training Contest 11 - Host by UESTC

解题:Palindromic Tree

#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
struct PalindromicTree{
int son[maxn][26],fail[maxn],len[maxn],s[maxn];
int tot,last,n;
int newnode(int slen = 0){
memset(son[tot],0,sizeof son[tot]);
len[tot] = slen;
return tot++;
}
void init(){
tot = last = n = 0;
newnode(0);
newnode(-1);
fail[0] = fail[1] = 1;
s
= -1;
}
int getFail(int x){
while(s[n - len[x] -1] != s
) x = fail[x];
return x;
}
void extend(int c){
s[++n] = c;
int cur = getFail(last);
if(!son[cur][c]){
int x = newnode(len[cur] + 2);
fail[x] = son[getFail(fail[cur])][c];
son[cur][c] = x;
}
last = son[cur][c];
}
}pt;
char str[maxn];
int main(){
int kase,cs = 1;
scanf("%d",&kase);
while(kase--){
scanf("%s",str);
pt.init();
for(int i = 0; str[i]; ++i)
pt.extend(str[i] - 'a');
printf("Case #%d: %d\n",cs++,pt.tot - 2);
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: