您的位置:首页 > 其它

uva 10716 - Evil Straw Warts Live

2013-08-16 20:26 495 查看

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

 

大致题意:给你一个字符串,看最少相邻移动n步后,是否可以成为回文字符串。

思路:先判断是否能成为回文字符串,如果有超过一个字母的个数是奇数的话,就不可能成为回文字符串。

这里是看的大神的:先把两边的变成一样的,依次递进。到最后。

#include <iostream>
#include <cstring>
#include <cstdio>
#include<cmath>
#include <algorithm>
using namespace std;

char a[110];
int b[1005];
void solve()
{
int i,j,k=0,n,m,p,q;
int t=strlen(a);
for(i=0;i<t;i++){ b[a[i]]++;}
for(j='a';j<='z';j++)
if(b[j]%2)
k++;
if(k>1)
{
printf("Impossible\n");
return;
}
int ans=0;
for(i=0;i<t/2;i++)
{
j=t-1-i;
for(n=i;a[j]!=a
;n++);
for(m=j;a[i]!=a[m];m--);
if(j-m<n-i)
{
ans+=j-m;
for(k=m;k<j;k++)
a[k]=a[k+1];
}
else
{
ans+=n-i;
for(k=n;k>i;k--)
a[k]=a[k-1];
}

}
printf("%d\n",ans);
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
memset(b,0,sizeof(b));
scanf("%s",a);
solve();

}
return 0;
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  贪心