Evil Straw Warts Live uva+回文串+贪心

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
解决方案:先预处理,如果出现次数为奇数的字母多于一个,那么必是Impossible。然后就是求最小移动的次数,可从两头到中间进行操作,如果相等,向里缩一个,不相等,则寻找步数最近的移动。
代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#define MMAX 103
using namespace std;
char word[MMAX];
int W[27];
int main(){
    int t;
    scanf("%d",&t);
    getchar();
    while(t--){
    gets(word);
    int f=0,sum=0;
    int len=strlen(word);
    memset(W,0,sizeof(W));
    for(int i=0;i<len;i++){
        W[word[i]-'a']++;
    }
    int cnt=0;
    for(int i=0;i<26;i++){
        if(W[i]%2!=0) cnt++;
    }
    if(cnt>=2) {printf("Impossible\n");continue;}
    int lens=len;
    for(int i=0;i<len/2;i++){
        if(word[i]==word[len-1-i]){
            continue;
        }
        else {
            int first=len-i-1;
            for(;word[first]!=word[i];first--);

            int second=i;
            for(;word[second]!=word[len-1-i];second++);

            if(len-1-i-first>second-i){

               for(int s=second;s>i;s--){
                word[s]=word[s-1];///移动时要注意,往那个方向移。
               }
               sum+=second-i;
            }
            else {

               for(int s=first;s<len-1-i;s++){
                word[s]=word[s+1];
               }
                sum+=len-1-i-first;


            }

    }


    } if(!f) printf("%d\n",sum);
    else printf("Impossible\n");


}
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值