前言
模拟赛有这道题,写篇题解纪念一下。
思路
题目等价于求当字符串为 形式时, 的长度。
考虑枚举 和 的长度,用哈希判断是否循环重构,代码如下,很好写:(注意,自然溢出哈希会被卡)
#include<bits/stdc++.h>
#define int unsigned long long
#define mod 998244353
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define req(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
#define re register
template <typename T> inline T read(T &x) { // 快读
x = 0; re char ch = getchar(); re int f = 1;
while (!isdigit(ch) && ch ^ '-') ch = getchar();
if (ch == '-') f = -1, ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar(); x *= f;
return x;
}
int n,Pow[10000001],Hash[10000001],ans;
string s;
bool same(int l1,int r1,int l2,int r2) // 判循环重构
{
return (Hash[r1]-Hash[l1-1]*Pow[r1-l1+1]%mod+mod)%mod==(Hash[r2]-Hash[l2-1]*Pow[r2-l2+1]%mod+mod)%mod;
}
main()
{
read(n);cin>>s;
Pow[0]=1;
rep(i,1,n) Pow[i]=Pow[i-1]*13331%mod,(Hash[i]=Hash[i-1]*13331+s[i-1])%=mod;
rep(i,1,n>>1) if(same(1,i,n-i+1,n)) // 枚举
{
ans=max(ans,i);
req(j,(n>>1)-i,1) if(same(i+1,i+j,n-i-j+1,n-i)) {ans=max(ans,i+j);break;}
}
cout<<ans;
return 0;
}于是测试点 #45、#50、#55 得到了 TLE,最终得分:70。
考虑进行优化:
令 ,那么原字符串也可以写成 ,将其分段为 。
记 表示 为 前 个字符时 的最大长度,则不难发现 ,是存在单调性的(类似于后缀数组求 )。我们可以知道初值 ,所以考虑 ,先计算 后计算 。
又因为我们前面发现的 (即 ),所以计算 时,先令其初值为 ,不合法就减小,总判断次数一定不超过 。
求出 数组后,判断 是否合法并更新答案即可。
总时间复杂度为 。
代码:
#include<bits/stdc++.h>
#define int long long
#define mod 998244853
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define req(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
#define re register
template <typename T> inline T read(T &x) { // 快读
x = 0; re char ch = getchar(); re int f = 1;
while (!isdigit(ch) && ch ^ '-') ch = getchar();
if (ch == '-') f = -1, ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar(); x *= f;
return x;
}
int n,Pow[10000001],Hash[10000001],dp[10000001],ans;
string s;
bool same(int l1,int r1,int l2,int r2) // 判断循环重构
{
return (Hash[r1]-Hash[l1-1]*Pow[r1-l1+1]%mod+mod)%mod==(Hash[r2]-Hash[l2-1]*Pow[r2-l2+1]%mod+mod)%mod;
}
main()
{
read(n);cin>>s;
Pow[0]=1;
rep(i,1,n) Pow[i]=Pow[i-1]*233%mod,(Hash[i]=Hash[i-1]*233+s[i-1])%=mod;
req(i,n>>1,1) // 优化
{
dp[i]=dp[i+1]+2;
if(dp[i]+i>(n>>1)) dp[i]=(n>>1)-i;
while(dp[i]&&!same(i+1,i+dp[i],n-i-dp[i]+1,n-i)) --dp[i];
}
rep(i,1,n>>1) // 判断 A 是否合法
if(same(1,i,n-i+1,n)) ans=max(ans,dp[i]+i);
cout<<ans;
return 0;
}