tag:blogger.com,1999:blog-4115025577315673827.post2184676579334717604..comments2020-05-25T13:34:36.365+05:30Comments on CSE Blog - quant, math, computer science puzzles: Cyclic StringsPratik Poddarhttp://www.blogger.com/profile/11577606981573330954noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-4115025577315673827.post-17075454807737927792010-09-08T02:06:47.321+05:302010-09-08T02:06:47.321+05:30Here, you have not considered that we can swap the...Here, you have not considered that we can swap the first and last element. In that case, number of swaps required can be lesser than the number of inversions.<br />eg. has 2n-2 inversions but by a single swap of n and 1, we get the correct permutation. I think the method of inversion pairs cannot be used in the above scenario.Unknownhttps://www.blogger.com/profile/09368486726435764689noreply@blogger.comtag:blogger.com,1999:blog-4115025577315673827.post-68674649034522305852009-11-08T00:03:58.166+05:302009-11-08T00:03:58.166+05:30Step1: Realise that this problem can be converted ...Step1: Realise that this problem can be converted into a simpler problem. By renumbering the numbers, I can always convert the problem to an equivalent problem where find the number of rotations such that the number of adjacent swaps required is minimum...<br />Also note that no. of adjacent swaps is number of moves required in bubble sorting method. This is equivalent to calculating the number of inversion pairs in an n-length array.<br /><br />Step2: The plan is to first calculate number of inversion pairs initially in O(nlog n). Then corresponding to each rotation, with O(nlog n) preprocessing time, we can find the number of inversion pairs in O(1). So, this is O(n logn) + O(n). Finding the minimum is O(1). So, the algorithm is O(nlog n)<br /><br />Done in many advanced algorithms courses, this problem can be solved by using divide and conquer in O(n log n). <br />This makes use of calculating the number of inversion pairs in two halves independently. "Conquering" is done by calculating the number of inversion pairs with left end in left part and right end in right part. This can be calculated and is a byproduct of merge sort algorithm. We get an O(n log n) algorithm to calculate the number of swaps.<br /><br />Now left is to give an algorithm to calculate number of inversion pairs in Permutation P2 from number of inversion pairs in Permutation P1, where P1 on cyclic rotation gives P2. Note that the only difference the two have is that the first number has moved to last. So, if we know the rank of the number in a sorted list, we can get it in O(1). Thats the O(n logn) preprocessing time we talked about. :)<br /><br />So, answer.<br /><br />Anyone can write it in a better way? ThanxPratik Poddarhttps://www.blogger.com/profile/11577606981573330954noreply@blogger.com