UVA - 10716
Description ![]() ![]() Problem D: Evil Straw Warts LiveA 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:
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 Input3 mamad asflkj aabb Output for Sample Input3 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 |
给出一个字符串,看这个字符串能否组成回文串,如果能则输出需要交换字母的次数,否则输出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;
}