fork download
  1. /*
  2. This solution uses DFS and iterative deepening, a technique where we search one layer deeper for solutions in each iteration.
  3. */
  4.  
  5. #include <iostream>
  6. using namespace std;
  7.  
  8. int n, exps[20];
  9. bool dfs (int dep, int maxDep) {
  10. if (dep > maxDep || exps[dep] << (maxDep - dep) < n) return false;
  11. if (exps[dep] == n) return true;
  12. for (int i = 0; i <= dep; i++) {
  13. for (int j : {-1, 1}) {
  14. exps[dep + 1] = exps[dep] + j * exps[i];
  15. if (exps[dep + 1] > 0 && dfs(dep + 1, maxDep)) return true;
  16. }
  17. }
  18. return false;
  19. }
  20.  
  21. int main () {
  22. while (cin >> n && n) {
  23. for (int d = 0;; d++) {
  24. exps[0] = 1;
  25. if (dfs(0, d)) {
  26. cout << d << endl;
  27. break;
  28. }
  29. }
  30. }
  31. }
Success #stdin #stdout 0.06s 5456KB
stdin
1
31
70
91
473
512
811
953
0
stdout
0
6
8
9
11
9
13
12