Advertisement
Kali_prasad

A20250408a_google_dp

Apr 9th, 2025
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. '''
  2. A20250408a_google_dp
  3. assume you were given an n fences
  4.  
  5. you need to paint them with k colours
  6.  
  7. thing is no more then 2 fences have same color
  8.  
  9. find the number of ways to make this possible
  10.  
  11. ---------------------------------------------------------------------------------------
  12.  
  13. important thing to be noted here is
  14.  
  15. this needs to be solved with dp states
  16.  
  17. assume you have matching btw i and i-1 treat this as dp 0 state for i
  18. assume you have no matching btw i and i-1 treat this as dp 1 state for i
  19.  
  20. soo
  21.  
  22. dp[i][0] = dp[i-1][1] #the i-1 cannot be matched with i-2 so only 1st state of i-1 is choosen ,that's it when matching requires you need to choose 1st state of i-1
  23. dp[i][1] = (k-1)*(dp[i-1][1] + dp[i-1][0])#now you do not care, whether i-1 matches with i-2 or not so taking both ways into consideration and multiplying those with left out paints count
  24.  
  25. k will be greater than 1
  26.  
  27. -----------------------------------------------------------------------------------------------------
  28. inputs - n and k
  29. 3
  30. 2
  31.  
  32. outputs -
  33. 6
  34.  
  35. '''
  36.  
  37. n = int(input())
  38. k = int(input())
  39. #we need 2 states here
  40. #i must be matching with i-1 is 0 state
  41. #i must not be matching with i-1 is 1 state
  42. dp = [ [0,0] for _ in range(n)]
  43. dp[0][0] = 0 #this is important ,there is no i-1 so you cannot match with i-1 color
  44. dp[0][1] = (k-1) + 1 #you dont care about i-1 ,which leaves you k-1 options ,but i-1 doesnt exist here so you can have total k as your choices here
  45. for i in range(1,n):
  46.     #if i need to match with i-1
  47.     dp[i][0] = dp[i-1][1] #the exact number of i-1 dp state that is not matching with i-2
  48.     #if i need not to match with i-1
  49.     dp[i][1] = (dp[i-1][1]+dp[i-1][0]) * (k-1) #now you need not to care whether i-1 matches with i-2 or not ,you are considering both states of it
  50.  
  51. finalAnswer = (dp[n-1][0]+dp[n-1][1])
  52. print(finalAnswer)
  53.  
  54.  
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement