建议升蓝。
考虑直接枚举 和 ,已经确定 和 的情况下,可以使用一个单调队列。这里在滑动一个长度为 的“大窗口”的同时需要存下每个长度为 的“小窗口”的字符串,比较的时候直接比较两个字符串的字典序。本质上还是滑动那个 的窗口,用来比较大小的值变成了一个长度为 的字符串。复杂度是 ,期望得分是 ,不过会被第 个点卡常卡到 分。因为不是正解所以也不特意去卡进两秒了。
#include<bits/stdc++.h>
using namespace std;
int ans[3005];
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
string s;cin>>s;
for(int k=1;k<=n;k++){
for(int l=1;l<=k;l++){
bool t[3005];for(int i=0;i<=n;i++)t[i]=0;
deque<pair<int,string>>q;
string nw=s.substr(0,l);
q.push_back({0,nw});
if(k==l)t[q.front().first]=1;
for(int i=1;i<=n-l;i++){
nw.erase(nw.begin());nw+=s[i+l-1];
while(!q.empty()&&q.back().second>nw)q.pop_back();
q.push_back({i,nw});
while(!q.empty()&&q.front().first+k<i+l)q.pop_front();
if(k<=i+l)t[q.front().first]=1;
}
int cnt=0;
for(int i=0;i<n;i++)if(t[i])cnt++;
ans[cnt]++;
}
}
for(int i=1;i<=n;i++)cout<<ans[i]<<endl;
return 0;
}那么有什么优化的方法呢?
注意到在上面的代码中我们需要滑动不同长度的窗口,但实际上判断子串,包括 q 里面存的等等都和 没关系,考虑直接计算出每个子串对不同 的贡献,而不是枚举每个 再重复取几遍这些子串。
首先不去管长度为 的字符串,假设这些都是数字,我们要做的是求出每个位置对 产生了多少贡献(对于每个 ,要么是 ,要么是 ),也就是看哪些 可能会选取这个数字为连续 个数的最小值。那么对于每个数只要知道它左边第一个小于等于它的数和右边第一个小于它的数的位置(记为 ),那么对应的 的范围就是 到 ,这个数就需要让 到 的这些 的“候选数字数量”(意义见题面)全部加上 。区间加一,求出最后所有数的值,可以用差分数组实现。
把上面提到的数字改成字符串,就可以完美解决本题的情况。还是一样,对于每个长度为 的子串,记录下左边第一个字典序小于等于它的子串位置 和右边第一个字典序小于它的子串位置 ,那么要加的 的范围就是 到 ,其中 是右边那个字符串的结束位置。
要记录一个数(字符串)两侧第一个小于等于或严格小于它的数(字符串),可以使用单调栈。
#include<bits/stdc++.h>
using namespace std;
int ans[3005],l[3005],r[3005],a[3005];
int main(){
ios::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
string s;cin>>s;
for(int L=1;L<=n;L++){
for(int i=0;i<=n;i++)a[i]=0,l[i]=-1,r[i]=n-L+1;
stack<pair<int,string>>st;
string nw=s.substr(0,L);
st.push({0,nw});
for(int i=1;i<=n-L;i++){
nw.erase(nw.begin());nw+=s[i+L-1];
while(!st.empty()&&st.top().second>nw)st.pop();
if(!st.empty())l[i]=st.top().first;
st.push({i,nw});
}
while(!st.empty())st.pop();
nw=s.substr(n-L,L);
st.push({n-L,nw});
for(int i=n-L-1;i>=0;i--){
nw.erase(nw.end()-1);nw=s[i]+nw;
while(!st.empty()&&st.top().second>=nw)st.pop();
if(!st.empty())r[i]=st.top().first;
st.push({i,nw});
}
for(int i=0;i<=n-L;i++){
a[L]++;
a[L+r[i]-l[i]-1]--;//(L+r[i]-l[i]-2)+1
}
for(int k=L;k<=n;k++){
a[k]+=a[k-1];
ans[a[k]]++;
}
}
for(int i=1;i<=n;i++)cout<<ans[i]<<endl;
return 0;
}