试题 基础练习 完美的代价
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。
交换的定义是:交换两个相邻的字符
例如mamad
第一次交换 ad : mamda
第二次交换 md : madma
第三次交换 ma : madam (回文!完美!)
输入格式
第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)
第二行是一个字符串,长度为N.只包含小写字母
输出格式
如果可能,输出最少的交换次数。
否则输出Impossible
样例输入
5
mamad
样例输出
3
题解: 使用C++
1.从左到右一直寻找配对,找到后缩小范围,L++,R–,然后将该字符移动到当前R的位置,并计算移动次数,找不到则失配次数num+1,继续寻找即L++
2.两种情况输出"impossible":
1)num>1;
2)num=1,但n为偶数;因为当n为奇数时,我们可以把这个唯一失配的数放到中间
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
const int N=8e3+9;
const int M=2e5+9;
#define gt getchar();
#define line '\n'
#define is isdigit
int read(){int x=0,op=1;char c=gt;while(!is(c)){if(c=='-')op=-1;c=gt;}while(is(c))x=x*10+c-48,c=gt;return x*op;}
char s[N];
int ans=0;
bool judge(int L,int R)
{
int r=R;
while(s[L]!=s[R])R--;
if(L==R)return false;
for(int i=R;i<r;++i)swap(s[i],s[i+1]),ans++;
return true;
}
int main()
{
int n=read();cin>>s;
int L=0,R=n-1,num=0,pos=-1;
while(L<R){
if(judge(L,R))L++,R--;
else L++,num++;
if(num>1)break;
if(num==1&&pos==-1)pos=L-1;
}
if(num>1)cout<<"Impossible"<<line;
else if(num==1){
if(n&1)cout<<ans+n/2-pos<<line;
else cout<<"Impossible"<<line;
}
else cout<<ans<<line;
return 0;
}