https://www.luogu.com.cn/problem/P3426
这题出得挺好的,代码量简洁但是却有一定思维量。
先说一下暴力做法,不难看出如果要完成这一工作,必然和前后缀有关,如果当前i的前后缀存在交叉,那么这一段一定可能成为答案。
若不交叉,则需要知道前缀被组成的串数,由于前缀可以被组成,前缀=后缀,所以后缀也可以被组成。因此我们关心中间的这一段能否被组成。
先说一下自己开始的错误dp想法。我开始是判前缀被组成的子串长度*2>=前缀即可转移。其实这个做法不能判断中间的一段是否能被组成。
想了一会想出了两个挺好的样例。
a b a b a b a b a b a b a
a b a b a c c c a b a b a
如果按照*2的做法来转移,那么下面的样例就会跑出答案为3.
所以我们要保证下面黄色部分也被覆盖。
图源:https://www.luogu.com.cn/user/276503
因此我们要记录每个前缀被覆盖的最新位置。也就是代码中的last[dp[i]]=i;
为什么要最新位置呢?看起来可以直接知道长度dp[d[i]-1]+d[i]>=i满足就行了。
举个例子:
aa
同样dp[0]=dp[1]=1。但是前面的串能被后面a组成。我们应该用的是后面的a的位置,即1的位置。(相当于变成一个新串不必考虑之前的串了,因为之前的串一定能被当前串覆盖)
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=5e5+100;
typedef int LL;
inline LL read(){
LL x=0,f=1;char ch=getchar(); while (!isdigit(ch)){
if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){
x=x*10+ch-48;ch=getchar();}
return x*f;}
char s[maxn];
LL d[maxn],dp[maxn],last[maxn];
inline void pre(const char* p,LL& n){
LL i=1,j=0;
while(i<n){
if(p[i]==p[j]){
d[i++]=++j;
}else{
if(j) j=d[j-1];
else i++;
}
}
}
inline void solve(const char* p){
LL n=strlen(p);
pre(p,n);
for(int i=0;i<n;i++) dp[i]=i+1;
//错误想法
// for(int i=1;i<n;i++){
// if(d[i]){
// if(d[i]*2>=i+1){
// dp[i]=min(dp[i],d[i]);
// }
// LL idx=d[i]-1;
// if(d[idx]*2>=d[i]){
// dp[i]=min(dp[i],dp[idx]);
// }
// }
// }
for(int i=0;i<n;i++){
if(d[i]){
///新开的这一段
if(d[i]*2>=i+1){
dp[i]=min(dp[i],d[i]);
}
///利用老的这一段
if(last[dp[d[i]-1]]+d[i]>=i){
dp[i]=min(dp[i],dp[d[i]-1]);
}
last[dp[i]]=i;
}
}
cout<<dp[n-1]<<endl;
}
int main(void){
cin.tie(0);std::ios::sync_with_stdio(false);
cin>>s;
solve(s);
return 0;
}