题目描述
Byteasar studies certain strings of zeroes and ones.
Let be such a string. By we will denote the reversed (i.e., "read backwards") string , and by we will denote the string obtained from by changing all the zeroes to ones and ones to zeroes.
Byteasar is interested in antisymmetry, while all things symmetric bore him.
Antisymmetry however is not a mere lack of symmetry.
We will say that a (nonempty) string is antisymmetric if, for every position in , the -th last character is different than the -th (first) character.
In particular, a string consisting of zeroes and ones is antisymmetric if and only if .
For example, the strings 00001111 and 010101 are antisymmetric, while 1001 is not.
In a given string consisting of zeroes and ones we would like to determine the number of contiguous nonempty antisymmetric fragments.
Different fragments corresponding to the same substrings should be counted multiple times.
对于一个01字符串,如果将这个字符串0和1取反后,再将整个串反过来和原串一样,就称作“反对称”字符串。比如00001111和010101就是反对称的,1001就不是。
现在给出一个长度为N的01字符串,求它有多少个子串是反对称的。
输入输出格式
输入格式:The first line of the standard input contains an integer () that denotes the length of the string.
The second line gives a string of 0 and/or 1 of length .
There are no spaces in the string.
输出格式:The first and only line of the standard output should contain a single integer, namely the number of contiguous (non empty) fragments of the given string that are antisymmetric.
输入输出样例
8
11001011
7
说明
7个反对称子串分别是:01(出现两次),10(出现两次),0101,1100和001011
Solution:
题意就是将一个01串每位上取反后再倒序形成新的01串,要使新串和原串相同。问一个01串有多少个子串满足条件。
本题正解貌似是hash。
但其实很简单,可以用修改的manacher来做,容易发现满足题中条件的01串必定满足:
1、串长为偶数(奇数显然取反后已经改变不会相同)
2、将串均分成两半,以中心对称的两位不同。(这条也是显然,但还是举个例子:1100 ,分成11|00,以竖线为中心,两边对称位置的数不同。)
3、由性质2,容易发现竖线为中心的半径长度,就是以该竖线为中心的满足条件的子串个数(举例:11|00,满足条件的有2个:1|0、11|00)。
4、显然,以竖线为中心,对称位置上的数字为中心所成满足条件的子串个数相同(举例:11|00,中间的1和0对称,以它们各自为中心,所成满足条件的子串个数都是0。)。
性质2、3明摆着很符合回文串的分半判断的性质!而且4性质恰好对应了manacher的dp优化初值的骚操作!
于是我们将manacher中的数组p[i](原含义:以i为中心的最长回文半径),改为表示:以i为中间两位中偏左的一位(如:11|00,i就是2)为标准已经能组成的满足条件的子串个数,则只需将p[i]初值赋为0再把判断条件改为s[i+p[i]+1]!=s[i-p[i]](唯一注意的是特判边界条件),最后ans累加p[i]就ok了。
代码:
#include<bits/stdc++.h> #define il inline #define ll long long #define N 500005 using namespace std; int p[N],n,cnt,id,mx; char s[N]; ll ans; int main() { scanf("%d%s",&n,s+1); for(int i=1;i<=n;i++){ if(i<mx)p[i]=min(p[id*2-i],mx-i); while(i+p[i]+1<=n&&i-p[i]>=1&&s[i+p[i]+1]!=s[i-p[i]])p[i]++; if(i+p[i]>mx)mx=i+p[i],id=i; ans+=p[i]; } cout<<ans; return 0; }