2013-07-07 18:18:18Morris
[UVA][greedy] 10716 - Evil Straw Warts Live
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
題目解法:
為了找到最少的交換次數,首先為奇數個數的字符最多只會有一個,先判斷是否有可能。
再者試圖先滿足最左右兩側的回文關係,先將中間剩餘還不是的回文字串,
決定讓一個字符同時轉到最左與最右,找一個字符的最少距離,然後將它轉到兩側。
接著再繼續解決中間部分的回文關係。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
int main() {
int testcase, i, j, k;
char s[105];
scanf("%d", &testcase);
while(testcase--) {
scanf("%s", s);
int n = strlen(s);
int cnt[128] = {}, odd = 0;
for(i = 0; i < n; i++)
cnt[s[i]-'a']++;
for(i = 0; i < 128; i++)
if(cnt[i]&1)
odd++;
if(odd > 1) {
puts("Impossible");
continue;
}
int ret = 0;
for(i = 0; i < n/2; i++) {
int mn[26] = {};
int mx[26] = {};
memset(mn, -1, sizeof(mn));
memset(mx, -1, sizeof(mx));
for(j = i; j < n-i; j++) {
if(mn[s[j]-'a'] == -1)
mn[s[j]-'a'] = j;
mx[s[j]-'a'] = j;
}
int mnswap = 0xffff, ch;
for(j = 0; j < 26; j++) {
if(mn[j] != -1) {
if((mn[j]-i) + (n-i-1 - mx[j]) < mnswap) {
mnswap = (mn[j]-i) + (n-i-1 - mx[j]);
ch = j;
}
}
}
for(j = mn[ch]; j > i; j--)
swap(s[j], s[j-1]), ret++;
for(j = mx[ch]; j < n-i-1; j++)
swap(s[j], s[j+1]), ret++;
}
printf("%d\n", ret);
}
return 0;
}