算法篇:贪心算法判断回文移动次数

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

 

/*贪心回文算法思想:用一个二重循环,相当于两个指针i,j,i从前往后,j从后往前,每次总是固定当前的i,

去寻找与之匹配的j,如果找到就将这个单词移动到尾部,并且跳出循环,进行下一个i的查找。如果没找到与i匹

配的j,即i=j的情况,说明当前i所指的这个字母是单独的,这时又分为两种情况:当n为偶数时,必为impossible;

当n为奇数时,出现两次单独的i才能确定为impossible,为此设立了一个flag标志,用来判断第几次出现单独的i的

情况。*/

 

#include<cstring>

#include<cstdlib>

#include<iostream>

#include<algorithm>

using namespace std;

int main(){

    int n;

    cin>>n;

    while(n--){

        string a;

        cin>>a;

    int cnt=0,flag=0;int f2=0;

    int l=a.length(); int end=l-1;

    for(int i=0;i<l/2+1;i++){

      for(int j=end;j>=i;j--){

         if(i==j){//没有与i对应位置字符匹配的情况

              if(l%2==0||flag==1){

               cout<<"Impossible"<<endl;

               f2=1;//f2是调试的过程中跳出两个for循环的标志。

               break;

              }

            flag=1;

            cnt+=l/2-i;//将单独的那个字符移动到中间位置

         }

         else if(a[i]==a[j]){//找到与i对应位置字符匹配的情况

              for(int k=j;k<end;k++){

                swap(a[k],a[k+1]); 

                cnt++;

              }

             end--;

             break;

         }

      }

      if(f2) break;

     }

     if(f2==0) cout<<cnt<<endl;

    }

    system("pause");

    return 0;

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ming__chen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值