fork(1) download
  1. We won't go through all numbers with two nested loops, but create a function f(prefix1, prefix2, sum) which will build the numbers digit by digit.
  2. For example, a pair of numbers (32, 567) would be built by adding digits, respectively, (0, 5), (3, 6), (2, 7).
  3.  
  4. Function f would look like this:
  5. f(prefix1, prefix2, sum):
  6. if prefixes are completely built, return sum
  7.  
  8. let (x, y) go through all possible pairs of digits:
  9. if you can add x on prefix1 and y on prefix2:
  10. call f(prefix1 * 10 + x, prefix2 * 10 + y, sum + |x – y|
  11.  
  12. This solution is not quicker than the two nested loops solution, but it can be tweaked. First we will get rid of the sum parametar from the function.
  13.  
  14. We will build a function num(prefix1, prefix2) which, for given prefixes of the first and second number, calculates the number of ways to "finish" these two numbers.
  15.  
  16. num(prefix1, prefix2):
  17. if prefixes are completely built, return 1
  18.  
  19. sol = 0
  20. let (x, y) go through all possible pairs of digits:
  21. if you can add x on prefix1 and y on prefix2:
  22. sol = sol + num(prefix1 * 10 + x, prefix2 * 10 + y)
  23. return sol
  24.  
  25. Now the function f can be transformed as follows:
  26.  
  27. f(prefix1, prefix2):
  28. if prefixes are completely built, return 0
  29.  
  30. sol = 0
  31. let (x, y) g through all possible pairs of digits:
  32. if you can add x on prefix1 and y on prefix2:
  33. sol = sol + num(prefix1 * 10 + x, prefix2 * 10 + y) * |x – y|
  34. sol = sol + f(prefix1 * 10 + x, prefix2 * 10 + y)
  35. return sol
  36.  
  37. The only thing left to notice is that we do not need to know the whole prefix in order to know whether we can add digit x.
  38. It is sufficient to know how many times we have added a digit before this one and has the prefix ever been different than the upper and lower interval bounds.
  39. This gives us a dynamical programming approach with O(number length * number of possible digits^2) complexity.
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
stdout
Standard output is empty