To solve this problem, we need to determine the minimum number of operations required to reduce a given number ( n ) to 1 using three possible operations: subtracting 1, dividing by 2 (if even), or dividing by 3 (if divisible by 3).
Approach
The problem can be efficiently solved using dynamic programming (DP). The key idea is to build up the solution by solving smaller subproblems and using their results to compute the solution for larger values of ( n ).
- Dynamic Programming Array: Let ( dp[i] ) be the minimum number of steps to reduce ( i ) to 1.
- Base Case: ( dp[1] = 0 ) (since we are already at 1).
- Transition: For each number ( i ) from 2 to ( n ):
- Start with the operation of subtracting 1: ( dp[i] = dp[i-1] + 1 ).
- If ( i ) is even, consider dividing by 2: ( dp[i] = \min(dp[i], dp[i//2] + 1) ).
- If ( i ) is divisible by 3, consider dividing by 3: ( dp[i] = \min(dp[i], dp[i//3] + 1) ).
This approach ensures that we always take the minimum steps for each number by considering all valid operations.
Solution Code
n = int(input())
dp = [0] * (n + 1)
for i in range(2, n + 1):
dp[i] = dp[i-1] + 1
if i % 2 == 0:
dp[i] = min(dp[i], dp[i//2] + 1)
if i % 3 == 0:
dp[i] = min(dp[i], dp[i//3] + 1)
print(dp[n])
Explanation
- Initialization: We create a DP array of size ( n+1 ) to store the minimum steps for each number from 0 to ( n ).
- Filling the DP Array: For each number ( i ):
- We first consider the operation of subtracting 1, which gives us ( dp[i-1] + 1 ) steps.
- If ( i ) is even, dividing by 2 gives us ( dp[i//2] +1 ) steps, so we take the minimum between the current value of ( dp[i] ) and this new value.
- Similarly, if ( i ) is divisible by 3, dividing by 3 gives us ( dp[i//3] +1 ) steps, and we again take the minimum.
- Result: The value at ( dp[n] ) gives the minimum steps to reduce ( n ) to 1.
This solution runs in ( O(n) ) time and uses ( O(n) ) space, which is efficient for large values of ( n ) (up to ( 10^6 ) or more). It correctly computes the minimum steps by leveraging dynamic programming to avoid redundant calculations.


作者声明:本文包含人工智能生成内容。