时间限制: 1 Sec 内存限制: 128 MB
题目描述
Let s be a given string of up to 106 digits. Find the maximal k for which it is possible to partition s into k consecutive contiguous substrings, such that the k parts form a palindrome.
More precisely, we say that strings s0, s1, . . . , sk−1 form a palindrome if si = sk−1−i for all 0 ≤ i < k.
In the first sample case, we can split the string 652526 into 4 parts as 6|52|52|6, and these parts together form a palindrome. It turns out that it is impossible to split this input into more than 4 parts while still making sure the parts form a palindrome.
输入
A nonempty string of up to 106 digits.
输出
Print the maximal value of k on a single line.
样例输入
复制样例数据
652526
样例输出
4
题解:字符串哈希,两边向中间判断即可
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e6 + 10;
ull bas = 233;
ull has[N];
char s[N];
int main() {
scanf("%s", s);
int len = strlen(s);
has[0] = 1;
for(int i = 1; i <= len; i++) has[i] = has[i - 1] * bas;
int ans = 0;
int i = 0, j = len - 1;
ull cnt1, cnt2;
int pre;
while(i <= j) {
cnt1 = s[i], cnt2 = s[j];
pre = j;
// cout << i << " " << j << endl;
while(cnt1 != cnt2) {
if(i + 1 >= j - 1) break;
i++;
j--;
cnt1 = cnt1 * 233 + s[i];
cnt2 = cnt2 + s[j] * has[pre - j];
}
if(cnt1 != cnt2) {
ans++;
break;
}
if(i != j)
ans += 2;
else
ans++;
i++; j--;
}
printf("%d\n", ans);
return 0;
}