题解:CF2276E Good Substrings
xujiachang · · 题解
CF2276E Good Substrings 题解
原题传送门
题意
给定一个长度为 2025 作为子序列,但不包含 2026 作为子序列。否则子串是好的。
对于每个位置
Solution
对于固定的左端点
那么对于以
- 若
r < point_{1} :不包含2025,是好的。 - 若
point_{1} \le r < point_{2} :包含2025但不包含2026,是坏的。 - 若
r \ge point_{2} :包含2026,是好的。
因此:
- 当
point_{1} \ge point_{2} 时,不存在坏子串,所有子串都是好的。 - 当
point_{1} < point_{2} 时,坏子串的右端点范围为[ point_{1}, point_{2}-1 ] 。
因此我们需要对每个位置
考虑每个左端点
-
默认贡献:假设所有子串都是好的,那么对于左端点
l ,右端点从l 到n 。对于位置i \ge l ,覆盖它的子串数量为n - i + 1 。\ 这可以看作在区间[l, n] 加上(n+1) - i 。 -
修正坏子串:如果
point_{1} < point_{2} ,则坏子串的右端点在[point_{1}, point_{2}-1] 。这些坏子串对位置i 的覆盖数量为:- 若
i < point_{1} :所有坏子串都覆盖i ,数量为point_{2} - point_{1} 。 - 若
point_{1} \le i \le point_{2}-1 :覆盖i 的坏子串数量为point_{2} - i 。 - 若
i \ge point_{2} :没有坏子串覆盖i ,数量为0 。
因此,我们需要从默认贡献中减去这个分段函数。
- 若
我们可以使用两个差分数组 cfk 和 cfm 来维护区间上的线性函数
- 默认贡献:在
[l, n] 上加上k = -1, m = n+1 。 - 若
point_{1} < point_{2} :- 在
[l, point_{1}-1] 上减去常数point_{2} - point_{1} (即加上k=0, m=-(point_{2}-point_{1}) )。 - 在
[point_{1}, point_{2}-1] 上减去point_{2} - i (即加上k=1, m=-point_{2} )。
- 在
最后对差分数组求前缀和,即可得到每个位置
预处理 nxt 数组
为了快速计算每个左端点 nxt[i][d]:\
表示从位置 cur[d] 为当前后缀中数字
然后对于每个 2025 和 2026 的匹配位置,每次跳转到 nxt[poi][digit]。由于模式串长度均为 4,每个
复杂度分析
- 预处理
nxt:O(10n) - 计算所有
l 的point_{1}, point_{2} :O(4n) - 差分更新:每个
l 常数次操作,O(n) - 前缀和还原答案:
O(n)
总时间复杂度
AC code
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int s2025[5]={0,2,0,2,5},s2026[5]={0,2,0,2,6};
int n;
string s;
int xxkan[300005][10]; //nxt数组
int qwq[10];
int cf1[300005]; //即k的差分
int cf2[300005]; //即m的差分
signed main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>s;
s=" "+s;
memset(qwq,0x3f,sizeof(qwq)); //多测不清空,亲人两行泪
for(int i=0;i<=n+2;i++) cf1[i]=cf2[i]=0;
for(int i=n;i>=1;i--) //预处理nxt数组
{
qwq[s[i]-'0']=i;
for(int j=0;j<=9;j++)
{
xxkan[i][j]=qwq[j];
}
}
for(int i=1;i<=n;i++)
{
int poi1=i,poi2=i,xx1=0,xx2=0;
while(xx1<4&&poi1<=n) poi1=xxkan[poi1][s2025[++xx1]]; //找到point1
while(xx2<4&&poi2<=n) poi2=xxkan[poi2][s2026[++xx2]]; //找到point2
if(poi1>n) poi1=n+1; //找不到
if(poi2>n) poi2=n+1;
cf1[i]--; //假设全都是好的
cf1[n+1]++;
cf2[i]+=n+1;
cf2[n+1]-=n+1;
if(poi1<poi2) //如果存在不好的序列在区间内
{
cf2[i]-=poi2-poi1; //将不好的序列删掉
cf2[poi1]+=poi2-poi1;
cf1[poi1]++;
cf1[poi2]--;
cf2[poi1]-=poi2;
cf2[poi2]+=poi2;
}
}
int cnt1=0,cnt2=0;
for(int i=1;i<=n;i++)
{
cnt1+=cf1[i];
cnt2+=cf2[i];
cout<<cnt1*i+cnt2<<" "; //对差分求前缀和,输出
}
cout<<"\n";
}
return 0;
}
本文使用 deepseek 进行了 latex 修正与格式调整。