[Solution] Palindrome Swaps CodeChef Solution
Problem
Chef has strings. Each string has length and consists only of lowercase english letters.
Chef likes palindromes, and would like each to be a palindrome. To achieve this, he can perform the following move:
- Pick an index such that and an index such that .
- Then, swap the character of string with the character of string .
Informally, Chef can swap the character of any two consecutive strings.
Find the minimum number of moves required to make every string a palindrome. Print if it is not possible to achieve this.
Input Format
- The first line of input contains a single integer , denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains two space-separated integers and , denoting the number of strings and their length, respectively.
- The of the next lines contains the string .
Output Format
- Print a single integer on a new line as the answer to each test case: the minimum number of swaps needed to make every a palindrome, or if this is not possible.
Explanation:
Test case : Chef can make all the strings palindromes in two operations:
- First, swap the second characters of and . Now, the strings are
- Then, swap the first characters of and . Now, the strings are , which are all palindromes.
Test case : Both strings are already palindromes.
Test case : It can be shown that it's impossible to make all strings simultaneously palindromes.
Test case : One optimal sequence of operations is as follows:
- Swap the first characters of and . Now, the strings are .
- Swap the second characters of and . Now, the strings are .
- Swap the fourth characters of and . Now, the strings are .
Thus, the final strings are all palindromes. It can be proven that we cannot achieve all palindromes in less than moves.
No comments:
Post a Comment