跳到正文

题解

题解:B4516 [四川青少年 C++ 算法设计大赛 2025] 醒来的统计

YCydd_约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年5月8日
收录
2026年5月9日
更新
2026年11月20日
篇幅
约 2 分钟
题目
B4516

版本

  1. v2当前
  2. v1

不开 long long 见祖宗!

问题理解

给定数字 xx 和最大允许出现次数 yy,求最大的正整数 nn,使得从 11 到 nn 的所有整数中,数字 xx 出现的总次数不超过 yy。

解题思路

由于 yy 最大可达 101810^{18},直接枚举 nn 并统计次数显然不可行。观察到随着 nn 增大,数字 xx 的出现次数单调递增,因此可以采用二分答案的方法,在 [1,1018][1,10^{18}] 范围内快速查找最大的可行 nn。

注意数据范围,开 long long!!!


YC 的 AC 代码,仅供参考!
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//不开 long long 见姥姥! 

ll cd(ll n,int x)
{
	if(n<=0) return 0;
	ll cnt=0;
	ll f=1;
	while(f<=n)
	{
		ll h=n/(f*10);
		ll c=(n/f)%10;
		ll l=n%f;
		if(x!=0)
		{
			if(c<x)
				cnt+=h*f;
			else if(c==x)
				cnt+=h*f+l+1;
			else
				cnt+=(h+1)*f;
		}
		else
		{
			if(h==0)
			{
				f*=10;
				continue;
			}
			if(c==0)
				cnt+=(h-1)*f+l+1;
			else
				cnt+=h*f;
		}
		f*=10;
	}
	return cnt;
}

int main()
{
	int x;
	ll y;
	cin>>x>>y;
	ll l=1,r=1e18;
	ll a=0;
	while(l<=r)
	{
		ll m=l+(r-l)/2;
		if(cd(m,x)<=y)
		{
			a=m;
			l=m+1;
		}
		else
			r=m-1;
	}
	cout<<a;
	return 0;
}

管理大大,求过!

原文