fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int minStepsToOne(int x) {
  5. vector<int> dp(x + 1, 0); // dp[i] = min steps to reduce i to 1
  6. dp[1] = 0; // base case
  7.  
  8. for (int i = 2; i <= x; i++) {
  9. int step1 = dp[i - 1];
  10. int step2 = (i >= 2) ? dp[i - 2] : INT_MAX;
  11. int step7 = (i % 7 == 0) ? dp[i / 7] : INT_MAX;
  12.  
  13. dp[i] = min({step1, step2, step7}) + 1;
  14. }
  15.  
  16. return dp[x];
  17. }
  18.  
  19. int main() {
  20. int x;
  21. cout << "Enter a number: ";
  22. cin >> x;
  23.  
  24. cout << "Minimum number of operations to reduce " << x << " to 1: " << minStepsToOne(x) << endl;
  25. return 0;
  26. }
  27.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Enter a number: Minimum number of operations to reduce 32767 to 1: 15