您的位置:首页 > 其它

UVA - 10716 - Evil Straw Warts Live (简单模拟)

2015-04-02 23:55 274 查看
UVA - 10716

Evil Straw Warts Live

Time Limit: 3000MSMemory Limit: Unknown64bit IO Format: %lld & %llu
Submit Status

Description







Problem D: 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"

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 100 lowercase letters. 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

Output for Sample Input

3
Impossible
2


Gordon V. Cormack

Source

Root :: AOAPC I: Beginning Algorithm Contests -- Training Guide (Rujia Liu) :: Chapter 1. Algorithm Design :: General Problem Solving Techniques :: Exercises:
Intermediate

Root :: AOAPC I: Beginning Algorithm Contests (Rujia Liu) :: Volume 4. Algorithm Design

Root :: Prominent Problemsetters :: Gordon V. Cormack
Submit Status
给出一个字符串,看这个字符串能否组成回文串,如果能则输出需要交换字母的次数,否则输出Impossible

AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;

int T;
int num[30];
char str[105];

int main() {
	scanf("%d", &T);
	while(T--) {
		memset(num, 0, sizeof(num));
		scanf("%s", str);
		int len = strlen(str), cnt = 0;
		for(int i = 0; i < len; i++) num[str[i] - 'a'] ++;
		for(int i = 0; i < 26; i++)
			if(num[i] & 1) cnt++;
		if(cnt >= 2) {
			printf("Impossible\n");
			continue;
		}
		
		int ans = 0, max = len - 1;
		for(int i = 0; i < len / 2; i++) {
			int j;
			for(j = max; j > i; j--) {
				if(str[j] == str[i]) break;
			}
			
			if(i == j) {
				swap(str[i + 1], str[i]);
				i--;
				ans++;
				continue;
			}
			
			ans += max - j;
			for(int k = j + 1; k <= max; k++) str[k - 1] = str[k];
			max--;
			
		}
		printf("%d\n", ans);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: