Advertisement
Kali_prasad

SORT_THEM

Dec 9th, 2024 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. # https://www.codechef.com/problems/SORT_THEM
  2. def sortedPos(ch):
  3.     sortedd = 'abcdefghijklmnopqrstuvwxyz'
  4.     return sortedd.find(ch)
  5. #you can directly do char comparision, instead of sortedPos comparision
  6. def checkIfSortable(s,p,lenn):
  7.     partner = p[::-1]
  8.     dp = [[float('inf')] * 2 for _ in range(lenn)]
  9.     dp[0]= [0,1]
  10.     #for a single char we dont need to care about prev ,just think what will be the result for single char s string
  11.     for ind in range(1,lenn):
  12.         prev = s[ind-1]
  13.         curr = s[ind]
  14.         '''
  15.        you can use the partner with index where you find the s char in p
  16.        partner is nothing but reversed p ,which satisfies x calculation for index i
  17.        so if you want p(x) just take partner(i)
  18.        '''
  19.         changedPrev = partner[p.find(prev)]
  20.         changedCurr = partner[p.find(curr)]
  21.         if sortedPos(prev)<=sortedPos(curr):#cond1
  22.             dp[ind][0] = dp[ind-1][0]
  23.         if sortedPos(changedPrev)<=sortedPos(curr):
  24.             dp[ind][0] = min(dp[ind][0],dp[ind-1][1])
  25.             '''
  26.            you are taking dp[ind][0] instead of dp[ind-1][0] for min operations, because you are not sure wether cond1 satisfied or not only dp[ind][0] will tell you at this point of time.
  27.            '''
  28.        
  29.        
  30.         if sortedPos(prev)<=sortedPos(changedCurr):
  31.             dp[ind][1] = 1+dp[ind-1][0]
  32.         if sortedPos(changedPrev)<=sortedPos(changedCurr):
  33.             dp[ind][1] = min(dp[ind][1],1+dp[ind-1][1])
  34.        
  35.     res = min(dp[lenn-1][0],dp[lenn-1][1])
  36.     return -1 if res==float('inf') else res
  37.  
  38. tc = int(input())
  39. for _ in range(tc):
  40.     lenn = int(input())
  41.     s = input()
  42.     p = input()
  43.    
  44.     print(checkIfSortable(s,p,lenn))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement