QueryreuQ Gym - 101806Q 求回文串个数

Statements
A string is palindrome, if the string reads the same backward and forward. For example, strings like “a”, “aa”, “appa”, “queryreuq” are all palindromes.

For given empty string S, you should process following two queries :

Add a lower case alphabet at the back of S.
Remove a character at the back of S.
After processing a query, you should count the number of palindrome substring in S. For string S and integers i,  j (1 ≤ i ≤ j ≤ |S|), represents a substring from ith to jth character of S. You should print out the number of integer pairs (i,  j) where is palindrome.

Input
Input consists of two lines.

In the first line, Q, the number of queries is given. (1 ≤ Q ≤ 10, 000)

In the second line, the query is given as string of length Q. ith character Ki denotes the ith query.

Ki is ‘-’ or lower case alphabet (‘a’, ‘b’, …, ‘z’) (without quotes).

If the character is ‘-’, you should remove a character at the back of S. If the character is lower case alphabet, you should add a character Ki at the back of S.

It is guaranteed that length of S is always positive after the query.

Output
Print out Q space-separated integers in the first line. i-th integer should be the answer of the ith query.

Example
Input
17
qu-uer-ryr-reu-uq
Output
1 2 1 2 3 4 3 4 5 7 5 7 9 11 9 11 13

题意:

给你一个串,’-'表示删除最后一个字符,其它表示在最后添加字符,问你每个操作之后这个字符串中有多少个回文串。

题解:

只需要纪录两个东西,一个是以当前位置为结尾的所有回文串的起始位置,一个是当前位置的答案。由于len-1的位置在上一次没法纪录,所以需要特判一下。举个例子:aaa在aa的位置的时候我知道了1和2是上一个回文串的起始位置,1之前没有字符了,所以只会比较第一个a和第三个a是否相等,因为我比较的是记录下来位置的前一个和当前,举个例子:aba在第二个字符的时候,我记录的是2,在第三个的时候比较的是3和(2-1)。所以答案就是ans[len-1]+vec[len].size()。

#include<bits/stdc++.h>
using namespace std;
#define sint short int
const int N=1e4+5;
vector<sint>vec[N];
int ans[N];
int main()
{
    int n;
    scanf("%d",&n);
    getchar();
    char a[N],s;
    int t=0,len=0;
    for(int i=1;i<=n;i++)
    {
        scanf("%c",&s);
        if(s=='-')
        {
            vec[t].clear();
            ans[t]=0;
            if(len>0)
                len--,t--;
            printf("%d\n",ans[t]);
            continue;
        }
        a[++len]=s;
        for(int j=0;j<vec[t].size();j++)
        {
            sint pos=vec[t][j];
            if(a[pos-1]==s)
                vec[t+1].push_back(pos-1);
        }
        if(s==a[len-1])
            vec[t+1].push_back(len-1);
        vec[t+1].push_back(len);
        t++;
        ans[t]=vec[t].size()+ans[t-1];
        printf("%d\n",ans[t]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值