资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。
交换的定义是:交换两个相邻的字符
例如mamad
第一次交换 ad : mamda
第二次交换 md : madma
第三次交换 ma : madam (回文!完美!)
输入格式
第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)
第二行是一个字符串,长度为N.只包含小写字母
输出格式
如果可能,输出最少的交换次数。
否则输出Impossible
样例输入
5
mamad
样例输出
3
程序
#include <iostream>
#include <cmath>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int len,count=0,flag=0;
string s;
cin>>len;
cin>>s;
int j=len-1;
for(int i=0;i<j;i++){
int k=j;
while(s[i]!=s[k]){
k--;
}
if(i==k){
if(len%2==0 || flag){
cout<<"Impossible";
return 0;
}
flag++;
count+=len/2-i;
}else{
while(k<j){
int temp=s[k];
s[k]=s[k+1];
s[k+1]=temp;
count++;
k++;
}
j--;
}
}
cout<<count;
return 0;
}