简要题意
给定一个长度为 的只由数字 到 组成的字符串 ,求 中有多少个子串满足 所有数字出现次数的最大值小于等于出现的不同数字的数量 ,其中 。
分析
题目拿到手,先想暴力解法。我们可以直接枚举 的所有子串,并统计子串中数字 出现的次数(记为 ),以及子串中 出现的数字个数 (记为 )。再记 ,比较 并记录答案即可。
for(int i=1;i<=n;i++){
memset(cnt,0,sizeof(cnt));
maxn=0;
sum=0;
for(int j=i;j<=n;j++){
int pos=a[j];
if(!cnt[pos]) sum++;
cnt[pos]++;
maxn=max(maxn,cnt[pos])
if(sum>=maxn) ans++;
}
}
显然,这种 的时间复杂度是过不去 的。所以我们考虑优化。
优化
显然,所有的数字个数不会超过 ,所以 ,而 ,所以可以得知符合条件的子串的长度一定不会大于 (每个数字各出现 次)。所以,我们可以将
for(ll j=i;j<=n;j++)
改成
for(ll j=0;j+i<=n&&j<=100;j++)
这样就可以将我们的时间复杂度优化到 ,轻松 AC 。
完整代码
#include<bits/stdc++.h>
#define ll long long
#define ma 214514
using namespace std;
ll read(){
char ch=getchar();
ll x=0,f=1;
while('0'>ch||ch>'9'){
if(ch=='-') f=-1;
ch=getchar();
}
while('0'<=ch&&ch<='9'){
x=x*10+ch-'0';
ch=getchar();
}
return x*f;
}
ll t;
ll n;
ll cnt[10];
ll maxn;
ll a[ma];
ll ans=0;
ll sum=0;
char x;
int main(){
t=read();
while(t--){
n=read();
memset(cnt,0,sizeof(cnt));
ans=0,sum=0;
for(ll i=1;i<=n;i++){
x=getchar();
a[i]=x-'0';//读入时转化成字符读入,防止读入一长串数字
}
for(ll i=1;i<=n;i++){
memset(cnt,0,sizeof(cnt));
maxn=0;
sum=0;
for(ll j=0;j+i<=n&&j<=100;j++){
ll pos=a[j+i];
if(!cnt[pos]) sum++;
cnt[pos]++;
maxn=max(maxn,cnt[pos]);
if(sum>=maxn) ans++;
}
}
printf("%lld\n",ans);
}
return 0;
}