BASIC-19 VIP试题 完美的代价

  • 从左到右一直寻找配对,找到后缩小范围,L++,R--,然后将该字符移动到当前R的位置,并计算移动次数,找不到则失配次数num+1,继续寻找即L++
    两种情况输出"impossible":
  • num>1;
  • 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;
}
posted @ 2020-04-17 20:42  啥也不是*  阅读(303)  评论(0)    收藏  举报