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"
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 8000 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 Impossible2
#include<cstdio> #include<iostream> #include<cstring> using namespace std; const int maxx=8001; char a[maxx]; int ispalindrome(){ //判断是否能成为回文串 int num[26]={0}; int count=0; int temp=strlen(a); for(int i=0;i<temp;i++){ num[a[i]-'a']++; } for(int i=0;i<26;i++){ if(num[i]%2==1){ count++; } } if(count>1){ return 1; } else{ return 0; } } int move(){ int count=0; //移动... int len=strlen(a)-1; int temp_l=0; int temp_r=strlen(a)-1; // printf("%c %c",r,l); if(temp_r<=temp_l){ printf("0\n"); return 0; } while(temp_r>temp_l){ int left_d,right_d,i,j; for(i=temp_l;i<temp_r;i++){ if(a[temp_r]==a[i]){ break; } } left_d=i-temp_l; for(j=temp_r;j>temp_l;j--){ if(a[temp_l]==a[j]){ break; } } right_d=temp_r-j; if(right_d>left_d){ count+=left_d; for(int k=left_d+temp_l;k>temp_l;k--){ swap(a[k],a[k-1]); } } else{ count+=right_d; for(int k=temp_r-right_d;k<temp_r;k++){ swap(a[k],a[k+1]); } } // printf("%s ",a); temp_r--; temp_l++; } printf("%d\n",count); } int main(){ // freopen("2.txt","r",stdin); int q; scanf("%d",&q); while(q--){ scanf("%s",&a); if(ispalindrome()){ printf("Impossible\n"); } else{ move(); } } return 0; }