题目描述:
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”
Input
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 8000 lowercase letters.
Output
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
Sample Output
3
Impossible
2
题意:
给你一个序列,问它们是否能够通过不断地交换成一个回文序列。
分析:
首先,要成为回文序列,那么必须字符串中的字符都要成对的出现。
当然,如果字符串的长度是奇数的话,是允许存在一个不成对的字符的。
参考博客:https://blog.csdn.net/qq_26919935/article/details/77769426
#include"stdio.h"
#include"string.h"
#include"algorithm"
using namespace std;
int main()
{
int T;
int vis[8010];
int mark[8010];
char str[8010];
while(~scanf("%d",&T))
{
while(T--)
{
memset(vis,0,sizeof(vis));
memset(mark,0,sizeof(mark));
scanf("%s",str);
int len=strlen(str);
int End=len-1;
int cnt=0;
for(int i=0;i<len;i++)
vis[str[i]-'a']++;
char V;
int flat=1;
for(int i=0;i<26;i++)
{
if(vis[i]%2)
{
cnt++;
if(cnt==2)
{
flat=0;break;
}
V='a'+i;
}
}
int step=0;
for(int i=0;i<len/2;i++)
{
int j;
for(int j=End;j>=i+1;j--)
{
if(str[i]==str[j])
{
mark[i]=1;
step+=End-j;//这是步数
for(int k=j;k<End;k++)
str[k]=str[k+1];
End--;
break;
}
}
}
if(len%2)//奇数的特判统计
{
for(int i=0;i<len;i++)
if(str[i]==V&&mark[i]==0)
{
step+=(len/2-i);break;
}
}
if(flat)
printf("%d\n",step);
else
printf("Impossible\n");
}
}
}