Advertisement
Fastrail08

Removing Digits

May 26th, 2025
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5. // CSES DP - Removing Digits - https://cses.fi/problemset/task/1637/
  6.  
  7. void getMinStepsToZero(int n, int steps, int &_min){
  8.     if(n == 0){
  9.         _min = min(steps, _min);
  10.         return;
  11.     }
  12.     int temp = n;
  13.     while(temp){
  14.         int option = temp % 10;
  15.         if(option != 0 && n - option >= 0){
  16.             getMinStepsToZero(n - option, steps + 1, _min);
  17.         }
  18.         temp /= 10;
  19.     }
  20. }
  21.  
  22. int getMinStepsToZeroMemo(int n, vector<int> &memo){
  23.     if(n == 0){
  24.         return 0;
  25.     }
  26.     if(memo[n] != INT_MAX){
  27.         return memo[n];
  28.     }
  29.     int temp = n;
  30.     int minAtEachLevel = INT_MAX;
  31.     while(temp){
  32.         int option = temp % 10;
  33.         if(option != 0 && n - option >= 0){
  34.             minAtEachLevel = min(minAtEachLevel, 1 + getMinStepsToZeroMemo(n - option, memo));
  35.         }
  36.         temp /= 10;
  37.     }
  38.     return memo[n] = minAtEachLevel;
  39. }
  40.  
  41. int getMinStepsToZeroDP(int n){
  42.     //Storage & Meaning - dp[i] = Minimum steps required from i to 0
  43.     vector<int> dp(n + 1, INT_MAX);
  44.    
  45.     // Direction - smallest problem at dp[0] - minimum step to reach 0 from 0;dp[0] = 0
  46.     //             largest problem at dp[n] - minimum step to reach 0 from n
  47.     dp[0] = 0;
  48.    
  49.     // Travel & Solve - Travel from smallest to largest subproblem, building the solution way up
  50.     for(int i = 1; i <= n; i++){
  51.         int temp = i;
  52.         while(temp){
  53.             int option = temp % 10;
  54.             if(option != 0){
  55.                 dp[i] = min(dp[i], 1 + dp[i - option]);
  56.             }
  57.             temp /= 10;
  58.         }
  59.     }
  60.     return dp[n];
  61. }
  62. int main() {
  63.     // your code goes here
  64.     int n;
  65.     cin >> n;
  66.     int _min = INT_MAX;
  67.     // getMinStepsToZero(n, 0, _min);
  68.     // cout << _min << '\n';
  69.     vector<int> memo(n + 1, INT_MAX);
  70.     cout << getMinStepsToZeroMemo(n, memo) << '\n';
  71.     cout << getMinStepsToZeroDP(n) << '\n';
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement