题解:P10279 [USACO24OPEN] The 'Winning' Gene S
建议升蓝。
考虑直接枚举
#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;
}