Gym - 100338E Numbers 贪心

 Gym - 100338E

题意:给你n,k问在1-n中能整出k的字典序最小的数。范围1018

思路:比较简单的贪心了,枚举10的幂m,然后加上k-m%k, 更新答案就可以了,数据一定要用unsigned long long,我就在这里挂了几次,查了半天。

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <fstream>
 4 #include <algorithm>
 5 #include <cmath>
 6 #include <deque>
 7 #include <vector>
 8 #include <queue>
 9 #include <string>
10 #include <cstring>
11 #include <map>
12 #include <stack>
13 #include <set>
14 #define LL unsigned long long
15 #define eps 1e-8
16 #define INF 0x3f3f3f3f
17 #define MAXN 10005
18 using namespace std;
19 LL n, k;
20 LL m[25];
21 //char s[25], res[25];
22 vector<char> s, t, res;
23 int main()
24 {
25 #ifdef ONLINE_JUDGE
26     freopen("numbers.in", "r", stdin);
27     freopen("numbers.out", "w", stdout);
28 #endif //ONLINE_JUDGE
29     m[0] = 1;
30     for (int i = 1; i <= 19; i++){
31         m[i] = m[i - 1] * 10ULL;
32     }
33     while (~scanf("%I64d%I64d", &n, &k)){
34         if (n == 0 && k == 0) break;
35         for (int i = 0; i <= 19; i++){
36             LL p = m[i] % k == 0 ? m[i] : m[i] + k - (m[i] % k);
37             if (p > n) break;
38             if (p % k != 0) continue;
39             t.clear();
40             while (p != 0){
41                 t.push_back(p % 10ULL + '0');
42                 p /= 10ULL;
43             }
44             s.clear();
45             for (int j = t.size() - 1; j >= 0; j--){
46                 s.push_back(t[j]);
47             }
48             if (i == 0){
49                 res = s;
50                 continue;
51             }
52             bool flag = true;
53             for (int j = 0; j < s.size(); j++){
54                 if (res.size() < j + 1){
55                     flag = true;
56                     break;
57                 }
58                 if (s[j] > res[j]){
59                     flag = true;
60                     break;
61                 }
62                 if (s[j] == res[j]) continue;
63                 flag = false;
64                 break;
65             }
66             if (flag) continue;
67             res = s;
68         }
69         for (int i = 0; i < res.size(); i++){
70             printf("%c", res[i]);
71         }
72         printf("\n");
73     }
74 }

 

posted on 2015-09-08 08:24  张济  阅读(146)  评论(0编辑  收藏  举报

导航