题解 - HDU Acesrc and Travel(想法+数学)

题解 - HDU Acesrc and Travel

题目链接: http://acm.hdu.edu.cn/status.php

题意:

定义一个函数 f ( d , n ) f(d,n) f(d,n) 的值为,在1到n中数字d出现的次数。

现在给出 Q Q Q个询问,每次询问 x , d x,d x,d ,求出最大的y满足 f ( d , y ) = = y & & y ≤ x f(d,y)==y \&\& y \le x f(d,y)==y&&yx

数据范围: 1 ≤ d ≤ 9 ; 1 ≤ x ≤ 1 0 18 ; 1\le d \le 9;1\le x \le 10^{18}; 1d9;1x1018;


思路:

假设当前求得的式子为 f ( d , x ) = y f(d,x) = y f(d,x)=y ,那么我们可以知道这个 y y y 与我们想要得到的 x x x 相差为 ∣ x − y ∣ |x-y| xy ,而我们所求的数据范围是 [ 1 , 1 0 18 ] [1,10^{18}] [1,1018] ,所以我们最多可以增加18个d,那么我们就每次向下减去 ⌈ ∣ x − y ∣ 18 ⌉ \lceil \frac {|x-y|} {18} \rceil 18xy 即可


代码:

#include <bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i = (int)j;i <= (int)k;i ++)
#define debug(x) cerr<<#x<<":"<<x<<endl
#define pb push_back

typedef long long ll;
typedef pair<int,int> pi;
const int MAXN = (int)1e6+7;

// 计算数字 X 在 1-n 中出现的次数。
ll count(ll n, ll x) {
    ll cnt = 0, k;
    for (ll i = 1;k = n / i;i *= 10) {
        // 高位的数字。
        ll high = k / 10;
        if (x == 0) {
            if (high) {
                high--;
            } else {
                break;
            }
        }
        cnt += high * i;
        // 当前位的数字。
        ll cur = k % 10;
        if (cur > x) {
            cnt += i;
        } else if (cur == x) {
            // n - k * i 为低位的数字。
            cnt += n - k * i + 1;
        }
    }
    return cnt;
}

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

    int T;
    cin >> T;
    while (T --) {
        ll d,x;
        cin >> d >> x;
        while (1) {
            ll res = count(x,d);
            if (res == x) break;
            ll cha = (abs(x-res)+17)/18;
            x -= cha;
        }
        cout << x <<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Best KeyBoard

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值