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 the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.
3 mamad asflkj aabb
3 Impossible 2
#include <iostream> #include <cstring> #include <cstdio> #include <string> #include <cmath> using namespace std; const int maxn = 110; string str; int letter[30]; void initial(){ for(int i = 0; i < 30; i++){ letter[i] = 0; } str.clear(); } void computing(){ for(int i = 0; i < str.length(); i++){ letter[str[i]-'a']++; } int odd = 0; for(int i = 0; i < 30; i++){ if(letter[i]%2) odd++; if(odd > 1){ printf("Impossible\n"); return; } } int l = 0 , r = str.length()-1 , ans = 0; while(l < r){ // cout << l << " " << r << endl; if(str[l] != str[r]){ int tl = 100000 , tr = 100000; for(int i = l+1; i < r; i++){ if(str[i] == str[l]) tr = i; if(str[i] == str[r] && tl == 100000) tl = i; } if(abs(tl - l) >= abs(r - tr)){ ans += r-tr; for(int i = tr; i < r; i++){ str[i] = str[i+1]; } str[r] = str[l]; }else{ ans += tl-l; for(int i = tl; i > l; i--){ str[i] = str[i-1]; } str[l] = str[r]; } } l++; r--; } printf("%d\n" , ans); } int main(){ int t; cin >> t; while(t--){ initial(); cin >> str; computing(); } return 0; }