Codeforces 489C - Given Length and Sum of Digits...(贪心)

题意

构造m位和为sum的最小和最大的数。

思路

一开始用了DFS,果断跪了。

贪心一下,如果要求最大的数,能填9的就填9,不够的补0,对于最小的数,先在第一位填1,然后从后面开始填9,不够补0,如果到了第一位有多的就全部加上去。

代码

 
  
  1. #include
  2. #include
  3. #include
  4. #include
  5. #include
  6. #include
  7. #include
  8. #include
  9. #include
  10. #include
  11. #include
  12. #include
  13. #include
  14. #include
  15. #define LL long long
  16. #define ULL unsigned long long
  17. #define SZ(x) (int)x.size()
  18. #define Lowbit(x) ((x) & (-x))
  19. #define MP(a, b) make_pair(a, b)
  20. #define MS(arr, num) memset(arr, num, sizeof(arr))
  21. #define PB push_back
  22. #define F first
  23. #define S second
  24. #define ROP freopen("input.txt", "r", stdin);
  25. #define MID(a, b) (a + ((b - a) >> 1))
  26. #define LC rt << 1, l, mid
  27. #define RC rt << 1|1, mid + 1, r
  28. #define LRT rt << 1
  29. #define RRT rt << 1|1
  30. #define BitCount(x) __builtin_popcount(x)
  31. #define BitCountll(x) __builtin_popcountll(x)
  32. #define LeftPos(x) 32 - __builtin_clz(x) - 1
  33. #define LeftPosll(x) 64 - __builtin_clzll(x) - 1
  34. const double PI = acos(-1.0);
  35. const int INF = 0x3f3f3f3f;
  36. using namespace std;
  37. const double eps = 1e-8;
  38. const int MAXN = 1000 + 10;
  39. const int MOD = 1000007;
  40. const int dir[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
  41. typedef pair<int, int> pii;
  42. typedef vector::iterator viti;
  43. typedef vector::iterator vitii;
  44. int minAns[MAXN], maxAns[MAXN];
  45. int main()
  46. {
  47. int m, sum, i, j;
  48. scanf("%d%d", &m, &sum);
  49. int leave = sum;
  50. if (m == 1 && sum == 0)
  51. {
  52. puts("0 0");
  53. return 0;
  54. }
  55. if (9 * m < sum || sum == 0)
  56. {
  57. puts("-1 -1");
  58. return 0;
  59. }
  60. minAns[0] = 1;
  61. leave--;
  62. for (int i = m - 1; i > 0; i--)
  63. {
  64. if (leave <= 9)
  65. {
  66. minAns[i] = leave;
  67. leave = 0;
  68. }
  69. else
  70. {
  71. minAns[i] = 9;
  72. leave -= 9;
  73. }
  74. }
  75. minAns[0] += leave;
  76. leave = sum;
  77. for (int i = 0; i < m; i++)
  78. {
  79. if (leave <= 9)
  80. {
  81. maxAns[i] = leave;
  82. leave = 0;
  83. }
  84. else
  85. {
  86. maxAns[i] = 9;
  87. leave -= 9;
  88. }
  89. }
  90. for (i = 0; i < m; i++) printf("%d", minAns[i]);
  91. printf(" ");
  92. for (i = 0; i < m; i++) printf("%d", maxAns[i]);
  93. return 0;
  94. }

你可能感兴趣的:(Codeforces 489C - Given Length and Sum of Digits...(贪心))