题目描述:
程序要求从键盘读入数据。第一行是一个整数N(N<=8000),表示所给字符串的长度,
第二行是所给的字符串,长度为N且只包含小写英文字母。如果所给字符串能经过若干次
交换变成回文串,则输出所需的最少交换次数;否则,输出Impossible。如下面两个例子:
例1:
5
mamad
3
例2:
6
aabbcd
Impossible
//回文串,从左往右和从右往左字符一样
//若一字符串可以成为字符串求交换的最少次数,若不能输出Impossible
//只允许相邻字符交换
...
#include <iostream>
#include <string>
#define swap(a, b) {int t = a; a = b; b = t;}
const int MAXN = 100;
int count;
using namespace std;
void Solve_(char* s, int ll)
{
if(s[0] == s[ll - 1]) return;
for(int i = 1; i < ll - 1; ++i){
if(s[i] == s[ll - 1]){
for(int k = i; k > 0; --k){
swap(s[k], s[k-1]);
count ++;}
return;
}
else if(s[0] == s[ll - i - 1]){
for(int k = ll - i - 1; k < ll - 1; ++k){
swap(s[k], s[k + 1]);
count ++;
}
return;
}
}
}
int main()
{
int N, len, app[26];
char str[MAXN];
memset(app, 0, sizeof(app));
freopen("F:\\input.txt", "r", stdin);
cin>> N;
cin>> str;
len = strlen(str);
for(int i = 0; i < len; ++i)
{
app[str[i] - 'a']++;
}
count = 0;
for(int i = 0; i < 26; ++i)
{
if(app[i]%2) count++;
}
if(count > 1) cout<< "Impossible"<< endl;
else
{
count = 0;
for(int i = 0; i < len/2; ++i){
Solve_(str + i, len - 2*i);
}
}
cout<< count;
return 0;
}