fork download
  1. #include <iostream>
  2. #include <cmath> // pow() and log10()
  3. #include <cstring> // memset()
  4. #include <algorithm> // std::min_element() and std::max_element()
  5.  
  6. using namespace std;
  7.  
  8. // Problem: http://n...content-available-to-author-only...r.net/Problem/Details/5621
  9.  
  10. int arr[18]; // Store the binary sequence
  11. int result[262144]; // (=2^18) Store the possible results of number z
  12. int a, b, na, nb, _index = 0, n = 0;
  13. /* a and b is the 2 numbers of input. na is the number of digit of a, nb is the number of
  14. digit of b, _index is the index of array result[], n is the number of elements of result[]*/
  15.  
  16. void Analyze(int a[])
  17. {
  18. /* "_na" is used with pow() of base 10 and mod 10 to take the first digit of "a" from
  19.   the left to the right. So is "_nb".
  20.   For instance: a = 584 => na = 3 => _na = 2 => (584 / 10^2) % 10 = 5 is the first digit
  21.   of a from the left to the right.
  22.   */
  23. int _na = na - 1, _nb = nb - 1, temp = na + nb - 1;
  24. for (int i = 0; i < (na + nb); ++i) {
  25. if (a[i] == 0) {
  26. int digit = static_cast<int>(::a/pow(10, _na--)) % 10;
  27. result[_index] += digit * pow(10, temp--);
  28. }
  29. else {
  30. int digit = static_cast<int>((::b)/pow(10, _nb--)) % 10;
  31. result[_index] += digit * pow(10, temp--);
  32. }
  33. }
  34. ++_index; // update the index of result[] for the next assignments.
  35. }
  36.  
  37. // Backtracking
  38. void ListBinary(int i)
  39. {
  40. // na + nb is the length of the binary sequence.
  41. if (i == (na + nb)) {
  42. /* Count if the number of value 0 in the binary sequence is equal to the length of
  43.   a and the number of value 1 in the binary sequence is equal to the length of b. */
  44. int zero = 0, one = 0;
  45. for (int i = 0; i < (na + nb); ++i) {
  46. if (arr[i] == 0)
  47. ++zero;
  48. else ++one;
  49. }
  50. /* If the binary sequence is appropriate, then we will use it to create a number
  51.   and put into the result[] */
  52. if (zero == na && one == nb) {
  53. ++n;
  54. Analyze(arr);
  55. }
  56. }
  57. else {
  58. arr[i] = 0;
  59. ListBinary(i + 1);
  60. arr[i] = 1; // backtrack
  61. ListBinary(i + 1);
  62. }
  63. }
  64.  
  65. int main()
  66. {
  67. memset(result, 0, 262144);
  68. cin >> a >> b;
  69. na = (int)log10(a) + 1;
  70. nb = (int)log10(b) + 1;
  71. ListBinary(0);
  72. cout << *min_element(result, result + n) << endl << *max_element(result, result + n);
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0s 16264KB
stdin
287 45
stdout
24587
45287