POI2010:ANT-Antisymmetry(二分 + HASH)

題目描述

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.

 

輸入輸出樣例

輸入樣例#1: 複製

8
11001011

輸出樣例#1: 複製

7

說明

7個反對稱子串分別是:01(出現兩次),10(出現兩次),0101,1100和001011

題意:求異或意義下的迴文串個數。

思路:正解是Manache算法變形先留坑,這裏用哈希做,符合的串肯定是偶數長且前後對應的字符相反,那麼把原串和反串都做一次哈希,然後枚舉分界點二分最遠的距離。

# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 5e5+30;
char s[maxn], t[maxn];
LL base[maxn]={1}, p[maxn], q[maxn];
const LL mod = 1e9+7, seed = 233;
LL Hash(int pos, int len, int flag)
{
    if(!flag) return (p[pos] - p[pos-len] * base[len] % mod + mod)%mod;
    else return (q[pos] - q[pos+len] * base[len] % mod + mod)%mod;
}
int cal(int pos, int len)
{
    if(s[pos] == s[pos+1]) return 0;
    int l=1, r=len;
    while(l <= r)
    {
        int mid = l + r >> 1;
        if(Hash(pos, mid, 0) == Hash(pos+1, mid, 1)) l = mid + 1;
        else r = mid - 1;
    }
    return r;
}
int main()
{
    int n;
    LL ans = 0;
    scanf("%d",&n);
    for(int i=1; i<=n; ++i) base[i] = base[i-1] * seed % mod;
    scanf("%s",s+1);
    for(int i=1; i<=n; ++i)
    {
        t[i] = '1' - s[i] + '0';
        p[i] = (p[i-1] * seed % mod + s[i]) % mod;
    }
    for(int i=n; i; --i)
        q[i] = (q[i+1] * seed % mod + t[i]) % mod;
    for(int i=1; i<n; ++i)
        ans += cal(i, min(i,n-i));
    printf("%lld\n",ans);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章