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"
Input
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 8000 lowercase letters.
Output
Output consists of one line per test case. This line will contain the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.
Sample Input
3 mamad asflkj aabb
Sample Output
3 Impossible 2
/*贪心回文算法思想:用一个二重循环,相当于两个指针i,j,i从前往后,j从后往前,每次总是固定当前的i,
去寻找与之匹配的j,如果找到就将这个单词移动到尾部,并且跳出循环,进行下一个i的查找。如果没找到与i匹
配的j,即i=j的情况,说明当前i所指的这个字母是单独的,这时又分为两种情况:当n为偶数时,必为impossible;
当n为奇数时,出现两次单独的i才能确定为impossible,为此设立了一个flag标志,用来判断第几次出现单独的i的
情况。*/
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
while(n--){
string a;
cin>>a;
int cnt=0,flag=0;int f2=0;
int l=a.length(); int end=l-1;
for(int i=0;i<l/2+1;i++){
for(int j=end;j>=i;j--){
if(i==j){//没有与i对应位置字符匹配的情况
if(l%2==0||flag==1){
cout<<"Impossible"<<endl;
f2=1;//f2是调试的过程中跳出两个for循环的标志。
break;
}
flag=1;
cnt+=l/2-i;//将单独的那个字符移动到中间位置
}
else if(a[i]==a[j]){//找到与i对应位置字符匹配的情况
for(int k=j;k<end;k++){
swap(a[k],a[k+1]);
cnt++;
}
end--;
break;
}
}
if(f2) break;
}
if(f2==0) cout<<cnt<<endl;
}
system("pause");
return 0;
}