【题解】P10976 统计重复个数 | 非倍增优化 DP 的做法
update 26.3.15: 修正 hack 数据
这道题目已有的题解中全部都是用倍增优化 DP 做的。但我觉得有个更自然的思路是,考虑循环节。
由于我的语言表述能力实在太差,本篇文章使用了 Deepseek 辅助完成。
为方便后文描述,我们定义匹配:如果
核心思路
首先考虑暴力,显然可以用贪心的思想用
int m=0,p=0;
for(int i=0;i<str1.size();i++){
if(str1[i]==str2[p]){
if(p+1==s2.size())m++,p=0;
else p++;
}
}
但
因为
于是我们将问题转换为:在
- 已使用的
s_1 周期数t_1 - 已完整匹配
s_2 的数量t_2
- 当发现某个位置
p 再次出现时,说明找到了循环
我已经尽力表达了……如果不理解的话可以看代码:
//需要先判断 s2 中的每个字符是否在 s1 中出现
//若否,则显然 m=0
using tp=tuple<int,int>;
int l1=s1.size(),l2=s2.size();
vector<tp>a(l1);//记录每个位置 p 第一次作为结尾时的 t1 和 t2
int p=l1-1,t1=0,t2=0;
while(1){
t2++;
for(int i=0;i<l2;i++){//O(|s2|)遍历
if(p+1==l1)p=0,t1++;else p++;
while(s1[p]!=s2[i]){
if(p+1==l1)p=0,t1++;else p++;
}//O(|s1|)找到第一个 s2[i],为了代码直观这里没有用预处理优化
}
if(a[p]==tp{0,0})a[p]={t1,t2};
else break;//如果这个位置之前已经作为结尾过了,说明找到循环
}
显然除最后一次循环外,每次最外层的 while 循环时 while 循环最多执行
这个没有优化的代码复杂度为
找到循环后,我们需要知道:
用以下样例举例:
abc 1
cab 4
显然我们会这样比配:
str1: cab cab cab cab
s2: ab cab cab c
而不是:
str1: cab cab cab cab
s2: ab c ab c
通过一坨代码可以计算出这些。
有了循环参数,我们可以把
- 整周期部分:前
\lfloor \frac{n_1-y}{T_1-y}\rfloor 个周期 - 余数部分:最后剩下的
(n_1 - y) \bmod (T_1 - y)+y 个s_1
得到总匹配数:
正确性证明
循环存在性证明:
- 状态空间有限:只有
|s_1| 个可能的位置 - 根据鸽巢原理,在
|s_1|+1 次匹配内必出现重复状态 - 一旦状态重复,后续行为必然重复
公式正确性证明:
- 整周期部分利用循环的周期性批量计算
- 余数部分处理剩余的不完整循环
- 相加覆盖所有
n_1 个周期
复杂度分析
- 状态数最多
|s_1| 个 - 每次匹配
s_2 需要O(|s_1||s_2|) 时间,通过预处理可以优化到O(|s_2|) 。 - 总复杂度
O(\sum|s_1||s_2|) 。由于|s_1|, |s_2| \leq 100 所以不写预处理优化复杂度为O(\sum|s_1|^2|s_2|) 也是完全可行的。
代码
懒得写预处理优化了。
#include<bits/stdc++.h>
using namespace std;
#define dbg(x) cerr<<#x<<':'<<(x)<<' '
#define dbe(x) cerr<<#x<<':'<<(x)<<endl
#define eb emplace_back
#define ep emplace
#define endl '\n'
using ll=long long;
using vi=vector<int>;
using vl=vector<ll>;
using tp=tuple<int,int>;
int main(){
cin.tie(0)->sync_with_stdio(0);
string s1,s2;
int n1,n2;
while(cin>>s2>>n2>>s1>>n1){
int l1=s1.size(),l2=s2.size();
vi bt(26);
for(auto c:s1)bt[c-'a']=1;
bool sf=true;
for(auto c:s2)if(bt[c-'a']==0){sf=false;break;}
if(!sf){cout<<0<<endl;continue;}
vector<tp>a(l1);
int p=l1-1,t1=0,t2=0,sc_p=-1;
while(1){
sc_p=p,t2++;
for(int i=0;i<l2;i++){
if(p+1==l1)p=0,t1++;else p++;
while(s1[p]!=s2[i]){
if(p+1==l1)p=0,t1++;else p++;
}
}
if(a[p]==tp{0,0})a[p]={t1,t2};
else break;
}
tie(t1,t2)=a[sc_p];
p=sc_p+1;
while(t2--){
for(int i=l2-1;i>=0;i--){
if(p-1==-1)p=l1-1,t1--;else p--;
while(s1[p]!=s2[i]){
if(p-1==-1)p=l1-1,t1--;else p--;
}
}
}
tie(t1,t2)=a[sc_p];
bool y=(sc_p<p);
ll M=(ll)(n1-y)/(t1-y)*t2,sx1=(n1-y)%(t1-y)+y,sx2=0;
for(auto [t1,t2]:a){
if(t1!=0&&t1<=sx1&&t2>sx2)sx2=t2;
}
M+=sx2;
cout<<M/n2<<endl;
}
return 0;
}
hack 数据
这个思路细节有点多,提供一组 hack 数据:
in:
abc 3
abcabcab 4
abd 3
abcabcab 4
aa 10
aaaa 4
cca 2
aac 10
cbbc 5
bbcabc 6
de 1
edededd 7
ans:
2
0
0
2
1
20
对拍好闪,拜谢对拍。
反正我把这些数据都调对了就 AC 了。