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;
}