试题 基础练习 完美的代价
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。
交换的定义是:交换两个相邻的字符
例如mamad
第一次交换 ad : mamda
第二次交换 md : madma
第三次交换 ma : madam (回文!完美!)
输入格式
第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)
第二行是一个字符串,长度为N.只包含小写字母
输出格式
如果可能,输出最少的交换次数。
否则输出Impossible
样例输入
5
mamad
样例输出
3
#include <iostream>
#include<string>
#include <map>
#include <algorithm>
using namespace std;
int main()
{
int n,judge = 0;
string s;
cin >> n >> s;
map<char, int> st;
for (int i = 0; i < n; i++) {
st[s[i]]++;
}
map<char, int>::iterator iter;
for (iter = st.begin(); iter != st.end(); iter++) {
if ((*iter).second % 2 == 1) { //有奇数个字母
judge++; //就加一
}
}
if (judge >= 2) //奇数个字母大于一个,就impossible
cout << "Impossible" << endl;
else {
int ans = 0;
int end = n;
for (int i = 0; i < (n + 1) / 2; i++) { //i从0到中间
int j;
for (j = end - 1; j > i; j--) { //j从最右边到i的位置
if (s[i] == s[j]) { //相等了就把s[j]移动到最右边
while (j < end - 1) {
swap(s[j], s[j + 1]);
j++;
ans++;
}
end--; //更新最右边的值
break;
}
}
if (i == j) {
ans += abs((n - 1) / 2 - i); //i和j相等说明是找到了单个字符,移动到中间需要的步数
}
}
cout << ans << endl;
}
return 0;
}