mukariwonderland何気ない日常で、ほんの少しの奇跡を見つける物語

CF1748B Diverse Substrings 题解

CF1748B Diverse Substrings 题解

题目传送门

简要题意

给定一个长度为 n 的只由数字 09 组成的字符串 s ,求 s 中有多少个子串满足 所有数字出现次数的最大值小于等于出现的不同数字的数量 ,其中 n105

分析

题目拿到手,先想暴力解法。我们可以直接枚举 s 的所有子串,并统计子串中数字 i 出现的次数(记为 cnti ),以及子串中出现的数字个数(记为 sum )。再记 maxn=max(cnti) ,比较 maxnsum 并记录答案即可。

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++;
}
}

显然,这种 O(n2) 的时间复杂度是过不去 n105 的。所以我们考虑优化。

优化

显然,所有的数字个数不会超过 10 ,所以 sum10 ,而 maxn105 ,所以可以得知符合条件的子串的长度一定不会大于 100 (每个数字各出现 10 次)。所以,我们可以将

for(ll j=i;j<=n;j++)

改成

for(ll j=0;j+i<=n&&j<=100;j++)

这样就可以将我们的时间复杂度优化到 O(n×100) ,轻松 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;
}
posted @   mukari  阅读(95)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示