题意:给出一个字符串,可以在字符串的右边任意添加字符,问最少添加多少个可以使新串成为回文串。
思路:manacher算法,求出以能到达右端点的最长回文串的长度,然后就可以轻松求出答案了。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#include<ctime>
#define eps 1e-6
#define LL long long
#define pii pair<int, int>
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;
const int MAXN = 1001000;
//const int INF = 0x3f3f3f3f;
int n;
char s[2*MAXN];
int p[2*MAXN];
void manacher() {
int len=strlen(s),id=0,maxlen=0;
for(int i=len;i>=0;--i){
s[i+i+2]=s[i];
s[i+i+1]='#';
}///插入了len+1个'#',最终的s长度是1~len+len+1即2*len+1,首尾s[0]和s[2*len+2]要插入不同的字符
s[0]='*';//s[0]='*',s[len+len+2]='\0',防止在while时p[i]越界
for(int i=2;i<2*len+1;++i){
if(p[id]+id>i)p[i]=min(p[2*id-i],p[id]+id-i);
else p[i]=1;
while(s[i-p[i]] == s[i+p[i]])++p[i];
if(id+p[id]<i+p[i])id=i;
if(maxlen<p[i]) maxlen=p[i];
}
}
int main() {
//freopen("input.txt", "r", stdin);
int T, kase = 0; cin >> T;
while(T--) {
scanf("%s", s);
int len = strlen(s), maxlen = 0;
manacher();
for(int i = 2; i < 2*len+1; i++) {
//cout << i-p[i] << " " << i+p[i] << endl;
if(i+p[i]-1==2*len+1) maxlen = max(maxlen, p[i]);
}
//cout << maxlen << endl;
printf("Case %d: ", ++kase);
cout << len + len - maxlen + 1 << endl;
}
return 0;
}