BZOJ 2084: [Poi2010]Antisymmetry

Description

对于一个01字符串,如果将这个字符串0和1取反后,再将整个串反过来和原串一样,就称作“反对称”字符串。比如00001111和010101就是反对称的,1001就不是。
现在给出一个长度为N的01字符串,求它有多少个子串是反对称的。

Input

第一行一个正整数N (N <= 500,000)。第二行一个长度为N的01字符串。


题解:

考虑回文自动机,由于反对称字符串一定是偶数,所以我们只需要维护偶回文树即可(即如果跳到root=1就停止跳fail),对于匹配反对称字符串,只需要修改一下回文自动机的匹配模式,让左右不相等,最后统计一下出现次数就好了。


AC代码:

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 5e5+50;
inline int read(){
    int x=0,f=1; char ch=getchar();
    while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch = getchar(); }
    while(ch>='0' && ch<='9') x=(x<<1)+(x<<3)+ch-48,ch=getchar();
    return x*f;
}
char s[MAXN];
int nxt[MAXN][2],fail[MAXN],len[MAXN];
int last,tot,cnt[MAXN],a[MAXN];
inline void Init(){
    last=tot=1;
    len[1]=-1,len[0]=0;
    fail[1]=0,fail[0]=1;
}
inline bool check(int en,int root){
    if((a[en]==a[en-len[root]-1] || en-len[root]-1==0) && root!=1) return true;
    return false;
}
inline void Insert(int x,int en){
    int root = last;
    while(check(en,root)) root=fail[root];
    if(root==1) { last=0;return; }
    if(!nxt[root][x]){
        int sz = ++tot;
        len[sz] = len[root]+2;
        int tmp = fail[root];
        while(check(en,tmp)) tmp=fail[tmp];
        if(tmp==1) fail[sz]=0;
        else fail[sz] = nxt[tmp][x];
        nxt[root][x] = sz;
    }
    last = nxt[root][x];
    ++cnt[last];
}
inline void Solve(){
    int ans = 0;
    for(int i=tot;i;i--) cnt[fail[i]] += cnt[i],ans += cnt[i];
    printf("%d\n",ans);
}
int main(){
    int n = read();
    scanf("%s",s+1);
    Init();
    for(int i=1;i<=n;i++) a[i]=s[i]-'0';
    for(int i=1;i<=n;i++) Insert(a[i],i);
    Solve();
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值