D. Palindrome Degree
题目连接:
http://www.codeforces.com/contest/7/problem/D
Description
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 exceed 5·106. The string is case-sensitive.
Output
Output the only number — the sum of the polindrome degrees of all the string’s prefixes.
Sample Input
a2A
Sample Output
1
Hint
题意
如果一个数是k回文串的话,那么他是回文串,且他的前半缀是k-1回文串,他的后半缀也是k-1回文串。
然后问你这个所有前缀的回文串等级的和是多少
题解:
跑的时候,维护这个前缀正着的的hash值,这个前缀倒着的hash值。
如果这两个hash值相同的话,说明这个串是一个回文串,那么他的等级d[i]=d[i/2]+1
然后跑一遍就好了
代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e7+5;
char s[maxn];
int dp[maxn];
long long p1=131,t1=1;
long long p2=127,t2=1;
long long h1=0,rh1=0;
long long h2=0,rh2=0;
int main()
{
scanf("%s",s+1);
long long ans = 0;
int l = strlen(s+1);
for(int i=1;i<=l;i++)
{
h1=h1*p1+s[i];
rh1=s[i]*t1+rh1;
t1=t1*p1;
h2=h2*p2+s[i];
rh2=s[i]*t2+rh2;
t2=t2*p2;
if(h1==rh1&&h2==rh2)
dp[i]=dp[i/2]+1;
ans+=dp[i];
}
cout<<ans<<endl;
}