serega1112

calc with answer

Jan 24th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.69 KB | None | 0 0
  1.  
  2. n = int(input())
  3.  
  4. dp = [float('inf')] * (n+1)
  5. dp[1] = 0
  6.  
  7. for i in range(1, n):
  8.     for op in range(1, 4):
  9.         if op == 1 and i + 1 <= n:
  10.             dp[i+1] = min(dp[i+1], dp[i] + 1)
  11.         elif op == 2 and i * 2 <= n:
  12.             dp[i*2] = min(dp[i*2], dp[i] + 1)
  13.         elif op == 3 and i * 3 <= n:
  14.             dp[i*3] = min(dp[i*3], dp[i] + 1)
  15.  
  16. res = []
  17.  
  18. pos = n
  19.  
  20. while pos != 1:
  21.     if dp[pos-1] == dp[pos] - 1:
  22.         res.append('1')
  23.         pos -= 1
  24.     elif pos % 2 == 0 and dp[pos//2] == dp[pos] - 1:
  25.         res.append('2')
  26.         pos //= 2
  27.     elif pos % 3 == 0 and dp[pos//3] == dp[pos] - 1:
  28.         res.append('3')
  29.         pos //= 3
  30.  
  31. print(''.join(res[::-1]))
Advertisement
Add Comment
Please, Sign In to add comment