POJ-1854 Evil Straw Warts Live

A palindrome is a string of symbols that is equal to itself when reversed. Given an input string, not necessarily a palindrome, compute the number of swaps necessary to transform the string into a palindrome. By swap we mean reversing the order of two adjacent symbols. For example, the string "mamad" may be transformed into the palindrome "madam" with 3 swaps: 
swap "ad" to yield "mamda" 
swap "md" to yield "madma" 
swap "ma" to yield "madam" 
Input
The first line of input gives n, the number of test cases. For each test case, one line of input follows, containing a string of up to 8000 lowercase letters.
Output
Output consists of one line per test case. This line will contain the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.
Sample Input
3
mamad
asflkj
aabb
Sample Output
3
Impossible

2

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;

const int maxx=8001;
char a[maxx];

int ispalindrome(){ //判断是否能成为回文串 
	int num[26]={0};
	int count=0;
	int temp=strlen(a);
	for(int i=0;i<temp;i++){
		num[a[i]-'a']++;
	}
	for(int i=0;i<26;i++){
		if(num[i]%2==1){
			count++;
		}
	}
	if(count>1){
		return 1;
	}
	else{
		return 0;
	}
} 

int move(){
	int count=0; //移动... 
	int len=strlen(a)-1;
	int temp_l=0;
	int temp_r=strlen(a)-1;
//	printf("%c %c",r,l);
	if(temp_r<=temp_l){
		printf("0\n");
		return 0;
	}
	while(temp_r>temp_l){
		int left_d,right_d,i,j;
		for(i=temp_l;i<temp_r;i++){
			if(a[temp_r]==a[i]){
				break;
			}
		}
		left_d=i-temp_l;
		for(j=temp_r;j>temp_l;j--){
			if(a[temp_l]==a[j]){
				break;
			}
		}
		right_d=temp_r-j;
		if(right_d>left_d){
			count+=left_d;	
			for(int k=left_d+temp_l;k>temp_l;k--){
				swap(a[k],a[k-1]);
			}
		}
		else{
			count+=right_d;
			for(int k=temp_r-right_d;k<temp_r;k++){
				swap(a[k],a[k+1]);
			}
		}
//		printf("%s ",a);
		temp_r--;
		temp_l++;
	}
	printf("%d\n",count);
}

int main(){
//	freopen("2.txt","r",stdin);
	int q;
	scanf("%d",&q);
	while(q--){
		scanf("%s",&a);
		if(ispalindrome()){
			printf("Impossible\n");
		}
		else{
			move();
		}
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值