PalindromeTime Limit: 6000/3000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)Total Submission(s): 770 Accepted Submission(s): 294 Problem Description Alice like strings, especially long strings. For each string, she has a special evaluation system to judge how elegant the string is. She defines that a string S[1..3n−2](n≥2) is one-and-half palindromic if and only if it satisfies S[i]=S[2n−i]=S[2n+i−2](1≤i≤n).For example, abcbabc is one-and-half palindromic string, and abccbaabc is not. Now, Alice has generated some long strings. She ask for your help to find how many substrings which is one-and-half palindromic. Input The first line is the number of test cases. For each test case, there is only one line containing a string(the length of strings is less than or equal to 500000), this string only consists of lowercase letters. Output For each test case, output a integer donating the number of one-and-half palindromic substrings. Sample Input 1 ababcbabccbaabc Sample Output 2 Hint In the example input, there are two substrings which are one-and-half palindromic strings, $abab$ and $abcbabc$. |
题意:
有多少对i,j(i<j)满足S[i-(j-i)...j],S[i...j+(j-i)]为回文串,即以i,j为中心的回文串能够相互覆盖到
做法:
我们设len[i]表示,以i为中心的回文半径可以用马拉车求解;
相互覆盖即: i+len[i]>=j j-len[j]<=i
j-len[j]<=i 可以用树状数组处理。
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int maxn=500005;
typedef long long ll;
vector<int> ve[maxn];
int a[maxn],n;
char s[maxn];
int Len[maxn],tlen[maxn];
int Manacher(char *st,int len){
int mx=0,ans=0,po=0;//mx即为当前计算回文串最右边字符的最大值
for(int i=1;i<=len;i++){
if(mx>i)
Len[i]=min(mx-i,Len[2*po-i]);//在Len[j]和mx-i中取个小
else
Len[i]=1;//如果i>=mx,要从头开始匹配
while(st[i-Len[i]]==st[i+Len[i]])
Len[i]++;
if(Len[i]+i>mx){//若新计算的 回文串右端点位置大于mx,要更新po和mx的值
mx=Len[i]+i;
po=i;
}
if(ans<Len[i]){
ans=Len[i];
}
}
return ans-1;//返回Len[i]中的最大值-1即为原串的最长回文子串额长度
}
int lowbit(int x){
return x&(-x);
}
void add(int pos,int v){
while(pos<=n){
a[pos]+=v;
pos+=lowbit(pos);
}
}
int query(int pos){
int ans=0;
while(pos){
ans+=a[pos];
pos-=lowbit(pos);
}
return ans;
}
int main(){
int t;
cin>>t;
while(t--){
memset(a,0,sizeof(a));
for(int i=0;i<maxn;i++)
ve[i].clear();
memset(s,0,sizeof(s));
scanf("%s",s+1);
int l=strlen(s+1);
s[0]='$';
Manacher(s,l);
for(int i=2;i<=l;i++){
tlen[i]=Len[i]-1;
ve[i-tlen[i]].push_back(i);
//cout<<i-tlen[i]<<endl;
}
ll ans=0; n=l;
for(int i=1;i<=n;i++){
for(int j=0;j<ve[i].size();j++){
//cout<<ve[i][j]<<endl;
add(ve[i][j],1);
}
//cout<<query(min(i+tlen[i],n))<<" "<<query(i)<<endl;
ans+=query(min(i+tlen[i],n))-query(i);
}
printf("%lld\n",ans);
}
return 0;
}