对于一个 \(0/1\) 串,若是取反后再将整个串反过来和原串同样,就称做「反对称」字符串ios
给出一个长度为 \(n\) 的 \(0/1\) 串,求它有多少个反对称子串spa
哈希题code
不难想到,预先处理出正向原串哈希值与反向取反串的哈希值ip
常规作法,暴力枚举区间断定,哈希值相等则加一字符串
可是数据范围 \(1\le n\le 500\ 000\) 显然会超时get
因而考虑二分string
二分枚举每一个区间的对称轴,每次对答案的贡献就是其半径hash
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #define maxn 1000100 #define LL long long #define uLL unsigned long long using namespace std; int n; LL ans; char s[maxn]; uLL b=1e9+7,Get[maxn],val[maxn],V[maxn]; inline int read(){ int s=0,w=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-') w=-1;ch=getchar();} while(ch>='0'&&ch<='9') s=(s<<1)+(s<<3)+ch-'0',ch=getchar(); return s*w; } inline int gethash2(int l,int r){return V[l]-V[r+1]*Get[r-l+1];} inline int gethash1(int l,int r){return val[r]-val[l-1]*Get[r-l+1];} inline bool check(int l,int r) {return gethash1(l,r)==gethash2(l,r);} inline int erfen(int i){ int l=0,r=min(i,n-i),Ans=0; while(l<=r){ int mid=(l+r)/2; if(check(i-mid+1,i+mid)){l=mid+1;Ans=mid;} else r=mid-1; } return Ans; } int main(){ n=read();scanf("%s",s+1); int len=strlen(s+1);Get[0]=1; for(register int i=1;i<=n;i++){ val[i]=val[i-1]*b+(uLL)s[i]; Get[i]=Get[i-1]*b; } for(register int i=n;i>=1;i--){ if(s[i]=='1') V[i]=V[i+1]*b+(uLL)'0'; else V[i]=V[i+1]*b+(uLL)'1'; } // for(register int i=1;i<n;i++) // for(register int j=i+1;j<=n;j++) // if(gethash1(i,j)==gethash2(i,j)) ans++; for(register int i=1;i<=n;i++) ans+=erfen(i); printf("%lld",ans); return 0; }