题解 - 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&&y≤x
数据范围: 1 ≤ d ≤ 9 ; 1 ≤ x ≤ 1 0 18 ; 1\le d \le 9;1\le x \le 10^{18}; 1≤d≤9;1≤x≤1018;
思路:
假设当前求得的式子为 f ( d , x ) = y f(d,x) = y f(d,x)=y ,那么我们可以知道这个 y y y 与我们想要得到的 x x x 相差为 ∣ x − y ∣ |x-y| ∣x−y∣ ,而我们所求的数据范围是 [ 1 , 1 0 18 ] [1,10^{18}] [1,1018] ,所以我们最多可以增加18个d,那么我们就每次向下减去 ⌈ ∣ x − y ∣ 18 ⌉ \lceil \frac {|x-y|} {18} \rceil ⌈18∣x−y∣⌉ 即可
代码:
#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;
}
}