码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-03 09:22:28      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:uva   acm   贪心   

UVA - 10716
Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

 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

 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;
} 












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

标签:uva   acm   贪心   

原文地址:http://blog.csdn.net/u014355480/article/details/44840641

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!