Problem Description
Acesrc is a famous mathematician at Nanjing University second to none. Playing with interesting numbers is his favorite. Today, he finds a manuscript when cleaning his room, which reads
... Let f(d,n) denote the number of occurrences of digit d in decimal representations of integers 1,2,3,⋯,n. The function has some fantastic properties ...
... Obviously, there exist some nonnegative integers k, such that f(d,k)=k, and I decide to call them d-good numbers ...
... I have found all d-good numbers not exceeding 101000, but the paper is too small to write all these numbers ...
Acesrc quickly recollects all d-good numbers he found, and he tells Redsun a question about d-good numbers: what is the maximum d-good number no greater than x? However, Redsun is not good at mathematics, so he wants you to help him solve this problem.
Input
The first line of input consists of a single integer q (1≤q≤1500), denoting the number of test cases. Each test case is a single line of two integers d (1≤d≤9) and x (0≤x≤1018).
Output
For each test case, print the answer as a single integer in one line. Note that 0 is trivially a d-good number for arbitrary d.
Sample Input
3
1 1
1 199999
3 0
Sample Output
1
199990
0
题意:t 组数据,定义函数 f(d,n) 为 1~n 的十进制位中数字 d 出现的个数,每组给出 d、x 两个数,现在要在 1~x 中找一个最大的 k,使得 f(d,k)=k,求这个 k
思路:
首先计算 f(d,x),如果 f(d,x)=x,那么自然就是结果
如果 f(d,x)
如果 f(d,x)>x,最坏的情况下,数的长度为 m 位,所有的位数都是 d,那么如果想让 f(d,x) 与 x 相等,至少要让他减去 f(d,x)-x/m 个数,因此在这种情况下,只要让 x=x-(f(d,x)-x)/m 即可
Source Program
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include