P3501-[POI2010]ANT-Antisymmetry【hash,二分答案】

正题

评测记录:https://www.luogu.org/recordnew/lists?uid=52918&pid=P3501


大意

一个01串,如果一个串翻转后取反和原串是相同的,那么这就是个反对称的。求这个01串有多少个子串是反对称的。


解题思路

一个反对称串就是将这个串取反然后放在原串后面的话是回文串,然后回文串是满足单调性的(如果以一个点为中心扩展k格是回文串,那么扩展k-1格也是回文串),所以我们可以枚举中心,然后二分最大的k,然后用hash判断回文。


code

#include<cstdio>
#include<cstring>
#include<iostream>
#define ull unsigned long long
#define N 500010
const ull hashmath=2000001001;
using namespace std;
int n;
ull wer[N],hash[N],rhash[N],ans;
char s[N];
bool check(int l,int r,int x)//判断回文
{
    ull s1,s2;
    int t1,t2;
    t1=l+x-1;t2=r+x-1;
    s1=hash[t1]-hash[l-1];
    s2=rhash[t2]-rhash[r-1];//前缀和
    if(l>r) {swap(s1,s2);swap(l,r);}
    s1*=wer[r-l];//减去差值
    return s1==s2;
}
int main()
{
    scanf("%d\n",&n);scanf("%s",s);wer[0]=1;
    for (int i=1;i<=n;i++) wer[i]=wer[i-1]*hashmath;
    for (int i=1;i<=n;i++)
      hash[i]=hash[i-1]+s[i-1]*wer[i];
    for (int i=1;i<=n/2;i++) swap(s[i-1],s[n-i]);
    for (int i=1;i<=n;i++)
      if (s[i-1]=='0') s[i-1]='1';
      else s[i-1]='0';//取反
    for (int i=1;i<=n;i++)
      rhash[i]=rhash[i-1]+s[i-1]*wer[i];
    for(int i=2;i<=n;i++)
    {
        int j=n-i+2,l=1,r=min(n-i+1,n-j+1);
        int maxs=0;
        while(l<=r){
            int mid=(l+r)>>1;//二分
            if(check(i,j,mid))
              maxs=max(mid,maxs),l=mid+1;
            else r=mid-1;
        }
        ans+=maxs;//统计答案
    }
    printf("%lld",ans);
}

猜你喜欢

转载自blog.csdn.net/Mr_wuyongcong/article/details/81745376