Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://www.codechef.com/problems/SORT_THEM
- def sortedPos(ch):
- sortedd = 'abcdefghijklmnopqrstuvwxyz'
- return sortedd.find(ch)
- #you can directly do char comparision, instead of sortedPos comparision
- def checkIfSortable(s,p,lenn):
- partner = p[::-1]
- dp = [[float('inf')] * 2 for _ in range(lenn)]
- dp[0]= [0,1]
- #for a single char we dont need to care about prev ,just think what will be the result for single char s string
- for ind in range(1,lenn):
- prev = s[ind-1]
- curr = s[ind]
- '''
- you can use the partner with index where you find the s char in p
- partner is nothing but reversed p ,which satisfies x calculation for index i
- so if you want p(x) just take partner(i)
- '''
- changedPrev = partner[p.find(prev)]
- changedCurr = partner[p.find(curr)]
- if sortedPos(prev)<=sortedPos(curr):#cond1
- dp[ind][0] = dp[ind-1][0]
- if sortedPos(changedPrev)<=sortedPos(curr):
- dp[ind][0] = min(dp[ind][0],dp[ind-1][1])
- '''
- 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.
- '''
- if sortedPos(prev)<=sortedPos(changedCurr):
- dp[ind][1] = 1+dp[ind-1][0]
- if sortedPos(changedPrev)<=sortedPos(changedCurr):
- dp[ind][1] = min(dp[ind][1],1+dp[ind-1][1])
- res = min(dp[lenn-1][0],dp[lenn-1][1])
- return -1 if res==float('inf') else res
- tc = int(input())
- for _ in range(tc):
- lenn = int(input())
- s = input()
- p = input()
- print(checkIfSortable(s,p,lenn))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement