POJ 1854 - Evil Straw Warts Live

本文介绍了一种算法,用于计算将任意字符串转换为回文串所需的最小交换次数。通过分治法从字符串两端逐步向中间逼近,找到匹配字符并计算交换步骤,最终实现高效转换。

Description

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

Source

Waterloo local 2004.09.19


输入一串字符,先判断是否可以通过变换顺序变成回文串,不是的话输出impossible。

然后如果possible,定义一次swap相邻两个字母为一步,计算这个字符串经过最少多少次swap可以变为回文串。

具体思维:使用分治的方法……

每次搞定最左边和最右边的两个字母,也就是从外向内一层层做成回文串。

比如 abcbac 这个,先看最左边的“a”,从最右边开始遍历字符串,找到的第一个“a”就可以经过最少次数把右边变成“a”,

再看最右边的“c”,同样的,从最左边遍历字符串,找到的第一个“c”就可以经过最少次数把右边变成“c”,

比较一下是把最外层变成两个a还是两个c……哪个划算,就加上这个步数,把字符串最外层排好:“abcbca”,then去掉最外层变成:“bcbc”,继续重复上面的工作……

#include<cstring>
#include<string>
using namespace std;
void swap_palindrome(char s[],int begin,int end,int &step)
{
	if(end-begin<=1) return;
	int i,left_distance,right_distance;
	for(i=begin;i<end;i++) if(s[i]==s[end]) break;
	left_distance=i-begin;
	for(i=end;i>begin;i--) if(s[i]==s[begin]) break;
	right_distance=end-i;
	if(left_distance<right_distance){
		step+=left_distance;
		for(int i=left_distance+begin;i>begin;i--) swap(s[i],s[i-1]);
	}else{
		step+=right_distance;
		for(int i=end-right_distance;i<end;i++) swap(s[i],s[i+1]);
	}
	swap_palindrome(s,begin+1,end-1,step);
}
int is_palindrome(char s[])
{
	int letter[26]={0},len=strlen(s);
	for(int i=0;i<len;i++) letter[ (s[i]-'a') ]++;
	int count=0;
	for(int i=0;i<26;i++){
		if(letter[i]%2==1) count++;
	}
	if(count>1) return 0;
	else return 1;
}
int main()
{
	int n;scanf("%d",&n);
	char s[8001];
	while(n--){
		scanf("%s",s);
		if(!is_palindrome(s)) printf("Impossible\n");
		else{
			int begin=0,end=strlen(s)-1,step=0;
			swap_palindrome(s,begin,end,step);
			printf("%d\n",step);
		}
	}
	return 0;
}

另外……这题,刚开始我用了string类型,cin输入,迭代器遍历……就time limit exceeded……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值