构造 Codeforces Round #135 (Div. 2) B. Special Offer! Super Price 999 Bourles!

题目传送门

 1 /*
 2    构造:从大到小构造,每一次都把最后不是9的变为9,p - p MOD 10^k - 1,直到小于最小值。
 3         另外,最多len-1次循环
 4 */
 5 #include <cstdio>
 6 #include <algorithm>
 7 #include <cstring>
 8 #include <cmath>
 9 using namespace std;
10 
11 typedef long long ll;
12 const int MAXN = 1e3 + 10;
13 const int INF = 0x3f3f3f3f;
14 
15 int get_len(ll x)   {
16     int ret = 0;
17     while (x)   {
18         x /= 10;    ret++;
19     }
20     return ret;
21 }
22 
23 int get_nine(ll x)  {
24     int ret = 0;
25     while (x)   {
26         ll y = x % 10;  x /= 10;
27         if (y != 9) break;
28         ret++;
29     }
30     return ret;
31 }
32 
33 int main(void)  {       //Codeforces Round #135 (Div. 2) B. Special Offer! Super Price 999 Bourles!
34     //freopen ("C.in", "r", stdin);
35     
36     ll p, d;
37     while (scanf ("%I64d%I64d", &p, &d) == 2)   {
38         int len = get_len (p);  ll now = p;
39         int mx = get_nine (p);  ll ans = p;
40         ll cut = 1;
41         while (true)    {
42             ll y = now / cut % 10;
43             if (y != 9) {
44                 now = now - cut * 10;    now = now / cut + cut - 1;
45             }
46             cut *= 10;
47             if (now < p - d)    break;
48             int cnt = get_nine (now);
49             if (cnt > mx)   ans = now;
50         }
51 
52         printf ("%I64d
", ans);
53     }
54 
55     return 0;
56 }
编译人生,运行世界!
原文地址:https://www.cnblogs.com/Running-Time/p/4661329.html