CF1748B Diverse Substrings 题解

题目传送门  博客园传送门

简要题意


给定一个长度为 $n$ 的只由数字 $0$ 到 $9$ 组成的字符串 $s$ ,求 $s$ 中有多少个子串满足 所有数字出现次数的最大值小于等于出现的不同数字的数量 ,其中 $n \le 10^5$

分析


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

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(n^2)$ 的时间复杂度是过不去 $n \le 10^5$ 的。所以我们考虑优化。

优化


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

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

改成

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

这样就可以将我们的时间复杂度优化到 $O(n\times 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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值