1. 程式人生 > >[洛谷P3501] [POI2010]ANT-Antisymmetry

[洛谷P3501] [POI2010]ANT-Antisymmetry

n) 回文字 eve har contain strings hat src 最長回文

洛谷題目鏈接:[POI2010]ANT-Antisymmetry

題目描述

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

簡述一下題意: 給出一個01串,要求出其中反對稱的回文字串的個數(就是將該字串反轉後每一位都不相同).

因為要求回文串的個數,所以我們可以考慮用manacher來做.我們知道,manacher算法是用來求最長回文的.那麽我們要怎麽樣才能求出回文個數呢?其實很簡單,就在處理回文串半徑的時候將每個回文的半徑都加入答案中就可以了.另外要註意一下只能記錄長度為偶數的回文字串,因為如果是奇數長度的回文串一定不滿足題意(想一下為什麽).

#include<bits/stdc++.h>
using namespace std;
const int N=10000000+5;
typedef long long lol;

int n, cnt, p[N*2];
lol ans = 0;
char s[N], ss[N*2], c[1000];

void init(){
    cnt = 1; ss[0] = '$', ss[cnt] = '#';
    for(int i=1;i<=n;i++)
    ss[++cnt] = s[i], ss[++cnt] = '#';
    c['0'] = '1', c['1'] = '0', c['#'] = '#';
    ss[cnt+1] = '*';
}

void manacher(){
    int id = 0, mx = 0;
    for(int i=1;i<=cnt;i++){
    if(i <= mx) p[i] = min(p[id*2-i],mx-i);
    else p[i] = 1;
    while(ss[i+p[i]] == c[ss[i-p[i]]]) p[i]++;
    if(mx < i+p[i]) mx = i+p[i], id = i;
    }
    for(int i=1;i<=cnt;i+=2)
    ans += (p[i]-1)/2;
}

int main(){
    //freopen("ghost.in","r",stdin);
    //freopen("ghost.out","w",stdout);
    cin >> n; scanf("%s",s+1);
    init(); manacher();
    printf("%lld\n",ans);
    return 0;
}

[洛谷P3501] [POI2010]ANT-Antisymmetry