CF1951E No Palindromes 另一种思路
yzc358230151 · · 题解
CF1951E
题意简述
划分给定字符串,使每一段均不回文或报告无解,多组数据。
分析
猜结论
非回文串的答案显然。
对于回文串,显然至少划分为
通过自行举例等方式可以猜想若有解存在一种解使得原串划分为
证明
假设法。
假设存在某个回文串
分类讨论:
- 假设
k=3 ,一种解中S 被划分为S[1..x],S[x+1\dots y],S[y+1\dots n] 。
那么:
- 划分出的串都不回文,即
S[1..x],S[x+1\dots y],S[y+1\dots n] 不回文。
这可以表示为以下三个式子:
\exist 0\le i\le x-1,S[1+i]\neq S[x-i] \exist 0\le i\le y-x-1,S[x+1+i]\neq S[y-i]\space (1) \exist 0\le i\le n-y-1,S[y+i+1]\neq S[n-i]
- 合并任意两个串,得到的串一定回文,即
S[1\dots y],S[x+1\dots n] 不回文。
否则合并后得到划分为
2 段的方案,与假设矛盾。该性质同样可以表示为以下两个式子:
\forall 0\le i\le y-1,S[1+i]=S[y-i]\space (2) \forall 0\le i\le n-x-1,S[x+1+i]=S[n-i]\space (3)
- 已经假设
S 为回文串。
式子表示:
\forall 0\le i\le n-1,S[1+i]=S[n-i]\space (4)
若我们合并上述的
而分析上述字符串长度或分析
所以
所以
我们发现,该式与前述
- 假设
k>3 ,一种解中划分开头的3 段为S[1\dots x],S[x+1\dots y],S[y+1\dots z]\space(z<n) ,对S[1\dots z] 作类似的分析也可得假设不成立,k \le 3 。
综上所述,原假设不成立,一定存在一种解使得回文串
代码实现
知道了这一点后,利用 Manacher 判断回文,枚举断点即可以
代码
#include<bits/stdc++.h>
using namespace std;
#define gc getchar
#define pc putchar
#define mkp make_pair
#define pb push_back
//typedef long long ll;
char str[1000010],str2[2000020];
int n,n2,r[2000020];
void huiwen(){
r[1]=1;
int box=1;
for(int i=2;i<=n2;++i){
int rr=i-box+1;
if(rr<=r[box]){
r[i]=min(r[box-rr+1],r[box]-rr+1);
}else
r[i]=1;
while(i-r[i]>=1&&i+r[i]<=n2&&str2[i+r[i]]==str2[i-r[i]])
++r[i];
if(i+r[i]-1>box+r[box]-1)
box=i;
}
}
bool chk(int L,int R){
int LL=(L<<1)-1,RR=(R<<1)-1;
int mid=(LL+RR)>>1;
// printf("checking %d->%d,on str2:%d->%d\n",L,R,LL,RR),
// printf("mid=%d,dis=%d,radius=%d\n",mid,RR-mid+1,r[mid]);
return RR-mid+1>r[mid];
}
void doit(){
scanf("%s",str+1),
n=strlen(str+1),
n2=(n<<1)-1;
for(int i=1;i<=n2;++i)
if(i&1)
str2[i]=str[(i+1)>>1];
else
str2[i]='#';
huiwen();
if(chk(1,n)){
fputs("YES\n1\n",stdout),
fputs(str+1,stdout),
fputs("\n",stdout);
return;
}else for(int i=2;i<=n;++i)
if(chk(1,i-1)&&chk(i,n)){
fputs("YES\n2\n",stdout);
char tmpch='\0';
swap(str[i],tmpch),
fputs(str+1,stdout),
fputs(" ",stdout),
swap(str[i],tmpch),
fputs(str+i,stdout),
fputs("\n",stdout);
return;
}
fputs("NO\n",stdout);
}
signed main(){
int T;
for(scanf("%d",&T);T;--T)
doit();
return 0;
}
后记
CF的题真的很容易被搬啊。
考试做到该题,听讲评和看题解发现思路大有不同,遂写题解。