您的位置:首页 > 其它

UVA 10716 Evil Straw Warts Live

2015-02-18 14:20 411 查看


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


把给定的字符串通过交换相邻位置的字母来变成回文串。
求最小的交换次数,每次贪心去找最近的。
#include<iostream>  
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<vector>
#include<functional>
#include<stack>
using namespace std;
const int maxn = 105;
int t, q, h, ff, tot, minn;
string s;
struct lf
{
	int l, r;
}; lf f[26];

int main(){
	cin >> t;
	while (t--)
	{
		cin >> s;	ff = 0;		memset(f, 0, sizeof(f));	tot = 0;
		for (int i = 0; i < s.size(); i++) f[s[i] - 'a'].l++;
		for (int i = 0; i < 26; i++) if (f[i].l & 1) ff++;
		if (ff <= 1)
		for (q = 0, h = s.size() - 1; q + 1 < h; q++, h--)
		{
			memset(f, 1, sizeof(f));
			for (int i = q; i <= h; i++)
			{
				f[s[i] - 'a'].l = min(i - q, f[s[i] - 'a'].l);
				f[s[i] - 'a'].r = min(f[s[i] - 'a'].r, h - i);
			}
			minn = 0;
			for (int i = 0; i < 26; i++)
				if (f[i].l + f[i].r<f[minn].l + f[minn].r) minn = i;
			tot += f[minn].l + f[minn].r;
			for (int i = q + f[minn].l; i > q; i--) swap(s[i], s[i - 1]);
			for (int i = h - f[minn].r; i < h; i++) swap(s[i], s[i + 1]);
		}
		if (ff > 1) printf("Impossible\n"); else printf("%d\n", tot);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: