fork(1) download
  1. #include<iostream>
  2.  
  3. struct DP
  4. {
  5. int firstDigit;
  6. int length;
  7.  
  8. DP(int firstDigit=0, int length=0) : firstDigit(firstDigit), length(length) { }
  9. };
  10.  
  11. const int MAX_N = 1000, MAX_ANS_LEN = 2*MAX_N;
  12. int N, TpowImodN[MAX_ANS_LEN+10];
  13. DP dp[MAX_N+10][MAX_N+10];
  14.  
  15. bool reduce(DP& what, DP competitor)
  16. {
  17. ++competitor.length;
  18. if ( what.length == 0
  19. || what.length > competitor.length
  20. || what.length == competitor.length && what.firstDigit > competitor.firstDigit)
  21. {
  22. what = competitor;
  23. return true;
  24. }
  25.  
  26. return false;
  27. }
  28.  
  29. void proceed(int sum, int rem)
  30. {
  31. for (int lastDigit = 9; lastDigit; --lastDigit)
  32. reduce(dp[sum+lastDigit][(rem*10+lastDigit)%N], dp[sum][rem]);
  33.  
  34. if (reduce(dp[sum][rem*10%N], dp[sum][rem]) && rem*10%N<rem)
  35. proceed(sum, rem*10%N);
  36. }
  37.  
  38. void printResult(std::string& res, int sum, int rem, int neededLen)
  39. {
  40. //std::cout<<"\nPRINT RESULT "<<sum<<" "<<rem<<" "<<neededLen<<"\n";
  41. if (sum==0 && rem==0 && neededLen==0)
  42. return;
  43.  
  44. int fd = dp[sum][rem].firstDigit;
  45. int len = dp[sum][rem].length;
  46. for (int i = len; i < neededLen; ++i)
  47. res += '0';
  48. res += char('0'+fd);
  49. printResult(res, sum-fd, (N+rem-fd*TpowImodN[len-1]%N)%N, len-1);
  50. }
  51.  
  52. std::string solve()
  53. {
  54. TpowImodN[0] = 1%N;
  55. for (int i = 1; i < MAX_ANS_LEN; ++i)
  56. TpowImodN[i] = TpowImodN[i-1]*10%N;
  57.  
  58. for (int i = 0; i < MAX_N+10; ++i)
  59. for (int j = 0; j < MAX_N+10; ++j)
  60. dp[i][j] = 0;
  61. //starting conditions
  62. for (int digit = 9; digit >= 0; --digit)
  63. dp[digit][digit%N] = DP(digit, 1);
  64.  
  65. //dp itself
  66. for (int sum = 1; sum <= N; ++sum)
  67. for (int rem = 0; rem < N; ++rem)
  68. if (dp[sum][rem].length)
  69. proceed(sum, rem);
  70.  
  71. //show();
  72.  
  73. std::string ans;
  74. printResult(ans, N, 0, dp[N][0].length);
  75. return ans;
  76. }
  77.  
  78. int main()
  79. {
  80. std::ios_base::sync_with_stdio(false);
  81. std::cin.tie(0);
  82. std::cout.tie(0);
  83.  
  84. int t;
  85. std::cin>>t;
  86. while (t--)
  87. {
  88. std::cin>>N;
  89. std::cout<<solve()<<"\n";
  90. }
  91. }
Runtime error #stdin #stdout 0s 11432KB
stdin
1000
stdout
Standard output is empty