http://codeforces.com/problemset/problem/7/D
String s of length n is called k-palindrome, if it is a palindrome itself, and its prefix and suffix of length are (k - 1)-palindromes. By definition, any string (even empty) is 0-palindrome.
Let’s call the palindrome degree of string s such a maximum number k, for which s is k-palindrome. For example, “abaaba” has degree equals to 3.
You are given a string. Your task is to find the sum of the palindrome degrees of all its prefixes.
Input
The first line of the input data contains a non-empty string, consisting of Latin letters and digits. The length of the string does not exceed5·106. The string is case-sensitive.
Output
Output the only number — the sum of the polindrome degrees of all the string’s prefixes.
Sample test(s) input
a2A
output
1
input
abacaba
output
6
题目大意:一个字符串是回文串有一定的水平值他的水平值:如果他的前一半串和后一半串是k-1水平,那么他就是k。
解题思路:用kmp,具体就是把原串当作匹配串,倒过来匹配,当匹配的长度,大于等于当前的下标,这说明出现回文了
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
const int N=5000006;
int next[N];
char a[N];
bool is[N];
int i,n,j,ans;
int count(int r)//返回的是以r为结尾的字符串水平值是多少
{
if(!r)
return 1;
int ret=1;
while(r>0)
{
r=(r-1)>>1;
if(is[r])
++ret;
else
break;
}
return ret;
}
int main()
{
while(~scanf("%s",a))
{
memset(is,0,sizeof(is));
n=strlen(a);
next[0]=j=-1;
for(i=1;i<n;i++)//KMP算法求next数组
{
while(j>-1&&a[j+1]!=a[i])
j=next[j];
if(a[j+1]==a[i])
++j;
next[i]=j;
}
j=-1;
for(i=n-1;i>=0;i--)//以原字符串为标准串于本身倒序匹配,当匹配结果大于等于一半是说明回文
{
while(j>-1&&a[j+1]!=a[i])
j=next[j];
if(a[i]==a[j+1])++j;
while(j>=i)
{
is[i+j]=1;
j=next[j];
}
}
for(ans=i=0;i<n;++i)
if(is[i])
ans+=count(i);
printf("%d\n",ans);
}
return 0;
}