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

· · 题解

不开 long long 见祖宗!

问题理解

给定数字 x 和最大允许出现次数 y,求最大的正整数 n,使得从 1 到 n 的所有整数中,数字 x 出现的总次数不超过 y。

解题思路

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

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

:::success[YC 的 AC 代码,仅供参考!]{open}

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

:::

管理大大,求过!