uva 10716 - Evil Straw Warts Live

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];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;
}



 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值