Description
对于一个01字符串,如果将这个字符串0和1取反后,再将整个串反过来和原串一样,就称作“反对称”字符串。比如00001111和010101就是反对称的,1001就不是。
现在给出一个长度为N的01字符串,求它有多少个子串是反对称的。
Sample Input
8
11001011
Sample Output
7
考虑字符串先做一遍hash,取反再做一遍hash。
然后二分判回文即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const ULL P = 131;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
int s = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
}
char ss[510000];
ULL s1[510000], s2[510000], o[510000];
int main() {
int n = read();
scanf("%s", ss + 1);
o[0] = 1; for(int i = 1; i <= n; i++) o[i] = o[i - 1] * P, s1[i] = s1[i - 1] * P + ss[i];
for(int i = 1; i <= n; i++) {
if(ss[i] == '0') ss[i] = '1';
else ss[i] = '0';
} for(int i = n; i >= 1; i--) s2[i] = s2[i + 1] * P + ss[i];
LL ans = 0;
for(int i = 1; i < n; i++) {
int l = 1, r = _min(i, n - i), hh = 0;
while(l <= r) {
int mid = (l + r) / 2;
if(s1[i + mid] - s1[i] * o[mid] == s2[i - mid + 1] - s2[i + 1] * o[mid]) l = mid + 1, hh = mid;
else r = mid - 1;
} ans += hh;
} printf("%lld\n", ans);
return 0;
}