Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of operations needed to decrease n to 0 in C++
Suppose we have a number n. Now consider an operation where we can either 1. Decrement n by one 2. If n is even number, then decrement it by n / 2 3. If n is divisible by 3, then decrement by 2 * (n / 3) Finally find the minimum number of operations required to decrement n to zero.
So, if the input is like n = 16, then the output will be 5, as n = 16 even then decreases it by n/2 4 times, it will be 1. Then reduce it by 1 to get 0. So total 5 operations.
To solve this, we will follow these steps −
Define one map dp
Define a function dfs(), this will take x,
ret := x
-
if x is in dp, then −
return dp[x]
-
if x <= 0, then −
return x
-
if x is same as 1, then −
return 1
md2 := x mod 2
md3 := x mod 3
ret := minimum of {ret, md2 + 1 + dfs((x - md2) / 2), md3 + 1 + dfs((x - md3) / 3)}
return dp[x] = ret
From the main method call and return dfs(n)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
unordered_map <int, int> dp;
int dfs(int x){
int ret = x;
if(dp.count(x))
return dp[x];
if(x <= 0)
return x;
if(x == 1)
return 1;
int md2 = x % 2;
int md3 = x % 3;
ret = min({ret, md2 + 1 + dfs((x - md2) / 2), md3 + 1 + dfs((x - md3) / 3)});
return dp[x] = ret;
}
int solve(int n) {
return dfs(n);
}
int main(){
int n = 16;
cout << solve(n);
}
Input
16
Output
5