题解:P3426 [POI 2005] SZA-Template
pioneer2000 · · 题解
题意:
求解最短的印章长度能使印章可以印完整一个字符串,其中
思路:
题意比较的好理解,接下来是思路。看到数据范围,不能想到可以进行
设
那么算法思路也就确定下来了。
我们在存一个数组
细节稍微注意一下即可。
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N=5e5+5;
string s;
ll nxt[N],f[N],g[N],n;
void nex(string x){//next数组求解模板
nxt[1]=0;
for(int cur=2,now=0;cur<=n;cur++){
while(now>0&&s[cur]!=s[now+1]){
now=nxt[now];
}
if(s[cur]==s[now+1]) now++;
nxt[cur]=now;
}
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>s;
n=s.size();
s=' '+s;
nex(s);
for(int i=1;i<=n;i++){//核心dp部分
f[i]=i;
if(g[f[nxt[i]]]>=i-nxt[i]){//好好想一想为什么这样就成立了
f[i]=f[nxt[i]];
}
g[f[i]]=i;
}
cout<<f[n];
return 0;
}