Description
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"
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
Source
输入一串字符,先判断是否可以通过变换顺序变成回文串,不是的话输出impossible。
然后如果possible,定义一次swap相邻两个字母为一步,计算这个字符串经过最少多少次swap可以变为回文串。
具体思维:使用分治的方法……
每次搞定最左边和最右边的两个字母,也就是从外向内一层层做成回文串。
比如 abcbac 这个,先看最左边的“a”,从最右边开始遍历字符串,找到的第一个“a”就可以经过最少次数把右边变成“a”,
再看最右边的“c”,同样的,从最左边遍历字符串,找到的第一个“c”就可以经过最少次数把右边变成“c”,
比较一下是把最外层变成两个a还是两个c……哪个划算,就加上这个步数,把字符串最外层排好:“abcbca”,then去掉最外层变成:“bcbc”,继续重复上面的工作……
#include<cstring>
#include<string>
using namespace std;
void swap_palindrome(char s[],int begin,int end,int &step)
{
if(end-begin<=) return;
int i,left_distance,right_distance;
for(i=begin;i<end;i++) if(s[i]==s[end]) break;
left_distance=i-begin;
for(i=end;i>begin;i--) if(s[i]==s[begin]) break;
right_distance=end-i;
if(left_distance<right_distance){
step+=left_distance;
for(int i=left_distance+begin;i>begin;i--) swap(s[i],s[i-]);
}else{
step+=right_distance;
for(int i=end-right_distance;i<end;i++) swap(s[i],s[i+]);
}
swap_palindrome(s,begin+,end-,step);
}
int is_palindrome(char s[])
{
int letter[]={},len=strlen(s);
for(int i=;i<len;i++) letter[ (s[i]-'a') ]++;
int count=;
for(int i=;i<;i++){
if(letter[i]%==) count++;
}
if(count>) return ;
else return ;
}
int main()
{
int n;scanf("%d",&n);
char s[];
while(n--){
scanf("%s",s);
if(!is_palindrome(s)) printf("Impossible\n");
else{
int begin=,end=strlen(s)-,step=;
swap_palindrome(s,begin,end,step);
printf("%d\n",step);
}
}
return ;
}
另外……这题,刚开始我用了string类型,cin输入,迭代器遍历……就time limit exceeded……