Problem D: edevil Straw Warts Live
A palindrome is a string of symbols that is equal to itself when reversed. given an input string, not necessarily a palindrome, compute the number of swaps necessary to transform the string into a palindrome. by swap we mean reversing the order of two adjacent symbols. for example, the string "mamad" may be transformed into the palindrome "madam" with 3 swaps:
Swap "ad" to yield "mamda"
Swap "md" to yield "madma"
Swap "ma" to yield "madam"
The first line of input gives n, the number of test cases. for each test case, one line of input follows, containing a string of up to 100 lowercase letters. output consists of one line per test case. this line will contain in the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.
Sample Input
3
Mamad
Asflkj
Aabb
Output for Sample Input
3
Impossible
2. Given some strings, it is required that you can convert them into Return Characters by exchanging letters .. If you can output the minimum number of transformations ..
Idea: greedy ..
1. First, determine whether it can be converted into a return text .. If no or only one letter in a string is an odd number. ..
2. Start with the first letter each time. Find the same letter from the back. In the end, it is matched .. The number of moves is the distance from the current position to the last position.
Note that a single letter is an odd number .. Finally, move the letter to the center .. We didn't consider this wa at the beginning --
Code:
# Include <stdio. h> # include <string. h> int t, len, sum, judge, end, vis [30], mark [105]; char sb [105], v; void Init () {sum = 0; judge = 1; memset (vis, 0, sizeof (vis); memset (mark, 0, sizeof (mark); gets (sb); len = strlen (sb ); end = len-1;} void Judge () {// you can determine whether the result can be a retrieval int bo = 0; for (int I = 0; I <len; I ++) vis [sb [I]-'a'] ++; for (int I = 0; I <26; I ++) {if (vis [I] % 2) {bo ++; if (bo = 2) {judge = 0; break;} v = I + 'A' ;}} void solve () {// transform for (int I = 0; I <len/2; I ++) {int j; for (j = end; j> = I + 1; j --) if (sb [j] = sb [I]) {mark [I] = 1; sum + = end-j; for (int k = j; k <end; k ++) sb [k] = sb [k + 1]; end --; break;} if (len % 2) {// for (int I = 0; I <len; I ++) if (sb [I] = v & mark [I] = 0) {sum + = len/2-I; break;} if (judge) printf ("% d \ n", sum); elseprintf ("Impossible \ n ");} int main () {scanf ("% d % * c", & t); while (t --) {Init (); Judge (); solve ();} return 0 ;}